In this post, we will learn how to reverse a stack. This is an important interview question.
Let’s have a look at the implementation in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//Reverse a stack public static class ReverseStack { //This method returns a stack public static Stack Reverse(Stack input) { Stack temp = new Stack(); while (input.Count != 0) temp.Push(input.Pop()); return temp; } } |
Here is working example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
//Reverse a stack public static class ReverseStack { //This method returns a stack public static Stack Reverse(Stack input) { Stack temp = new Stack(); while (input.Count != 0) temp.Push(input.Pop()); return temp; } } class Program { public static void Main() { Stack st = new Stack(); st.Push(10); st.Push(5); st.Push(11); st.Push(7); st.Push(100); Console.WriteLine("\n..::Before reversing::.."); foreach (var item in st) { Console.WriteLine(item); } st = ReverseStack.Reverse(st); //reverse stack Console.WriteLine("\n..::After reversing::.."); foreach (var item in st) { Console.WriteLine(item); } Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
..::Before reversing::.. 100 7 11 5 10 ..::After reversing::.. 10 5 11 7 100 |