Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
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
Advertisements
