Reverse a Stack using C#


Set a stack and add elements to it.

Stack st = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R');

Now set another stack to reverse it.

Stack rev = new Stack();

Until the count of ths Stack is not equal to 0, use the Push and Pop method to reverse it.

while (st.Count != 0) {
   rev.Push(st.Pop());
}

The following is the complete code −

Example

 Live Demo

using System;
using System.Collections;

namespace CollectionsApplication {
   public class Program {
      public static void Main(string[] args) {
         Stack st = new Stack();
         Stack rev = new Stack();
         st.Push('P');
         st.Push('Q');
         st.Push('R');
         Console.WriteLine("Current stack: ");
         foreach(char c in st) {
            Console.Write(c + " ");
         }
         Console.WriteLine();
         while (st.Count != 0) {
            rev.Push(st.Pop());
         }
         Console.WriteLine("Reversed stack: ");
         foreach(char c in rev) {
            Console.Write(c + " ");
         }
      }
   }
}

Output

Current stack:
R Q P
Reversed stack:
P Q R

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements