How can I reverse a stack?
I need to write a VB.NET code to reverse the given characters using a stack. Input: 'S','T','A','C','K'
So far I have input the letters, but I don't know how to get the console to reverse it. I'm a beginner to programming so please excuse my ignorance.
An explanation as to how it's done would also be greatly appreciated.
What I got so far.
Module Module1
Sub Main()
Dim StackObject As New Stack
StackObject.Push("S")
Console.WriteLine(StackObject.Peek)
StackObject.Push("T")
Console.WriteLine(StackObject.Peek)
StackObject.Push("A")
Console.WriteLine(StackObject.Peek)
StackObject.Push("C")
Console.WriteLine(StackObject.Peek)
StackObject.Push("K")
Console.WriteLine(StackObject.Peek)
End Sub
End Module
I just need it to be reversed.
I got it!!
Module Module1
Sub Main()
Dim StackObject As New Stack
StackObject.Push("S")
StackObject.Push("T")
StackObject.Push("A")
StackObject.Push("C")
StackObject.Push("K")
For Each cur As String In StackObject
Console.WriteLine(cur)
Next
End Sub
End Module
That's how it's done开发者_如何转开发.
Say you had a stack of plates:
1
2
3
4
5
To reverse them, you take the first plate off, then drop it onto a new pile
2
3
4
5 1
Then you take the next plate off and drop it on the pile.
3
4 2
5 1
Repeat!
Pseudo-code (I really don't know VB.NET):
While (not end-of-input) Do Stack.Push(ReadNextInputChar);
While (not Stack.IsEmpty) Do WriteCharToOutput(Stack.Pop);
Module Module1
Sub Main()
Dim StackObject As New Stack
StackObject.Push("S")
StackObject.Push("T")
StackObject.Push("A")
StackObject.Push("C")
StackObject.Push("K")
For Each cur As String In StackObject
Console.WriteLine(cur)
Next
End Sub
End Module
I'm not sure about the VB syntax, But this is how we can proceed to reverse a stack. This is in-place too. (it makes use of recursion)
void appendToStack (std::stack<int> &stk, int newElement)
{
if (stk.empty())
stk.push(newElement);
else
{
int oldElement = stk.top();
stk.pop();
appendToStack (stk, newElement);
stk.push (oldElement);
}
}
void reverseStackInplace (std::stack<int> &stk)
{
if (stk.empty())
return;
int element = stk.top();
stk.pop();
reverseStackInplace(stk);
appendToStack (stk, element);
}
精彩评论