C# program to reverse a Stack
Here's a C# program that reverses a built-in Stack using an auxiliary stack:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Stack stack = new Stack();
stack.Push(1);
stack.Push(2);
stack.Push(3);
stack.Push(4);
stack.Push(5);
Console.WriteLine("Original Stack:");
PrintStack(stack);
Stack reversedStack = ReverseStack(stack);
Console.WriteLine("Reversed Stack:");
PrintStack(reversedStack);
}
public static Stack ReverseStack(Stack stack)
{
Stack reversedStack = new Stack();
while (stack.Count > 0)
{
reversedStack.Push(stack.Pop());
}
return reversedStack;
}
public static void PrintStack(Stack stack)
{
foreach (T item in stack)
{
Console.WriteLine(item);
}
}
}
In this program, we create an instance of the generic 'Stack' class from the 'System.Collections.Generic' namespace. We use the 'Push' method to add elements to the stack.
The 'ReverseStack' method takes a 'Stack' as input and returns a reversed stack. It creates a new 'Stack' called 'reversedStack' and iterates over the original stack using a 'while' loop. In each iteration, it pops an item from the original stack and pushes it onto the 'reversedStack'. Once the original stack becomes empty, the reversed stack will contain the elements in reverse order.
The 'PrintStack' method is a utility method that prints the contents of a stack to the console.
In the 'Main' method, we create a 'Stack' object and push some integers onto the stack. We then call the 'ReverseStack' method to reverse the stack and store the result in a new stack called 'reversedStack'. Finally, we print both the original stack and the reversed stack to the console.