ตั้งค่าสแต็กและเพิ่มองค์ประกอบเข้าไป
Stack st = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R'); ตอนนี้ตั้งค่าสแต็กอื่นเพื่อย้อนกลับ
Stack rev = new Stack();
จนกว่าจำนวน Stack จะไม่เท่ากับ 0 ให้ใช้วิธี Push and Pop เพื่อย้อนกลับ
while (st.Count != 0) {
rev.Push(st.Pop());
} ต่อไปนี้เป็นรหัสที่สมบูรณ์ -
ตัวอย่าง
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 + " ");
}
}
}
} ผลลัพธ์
Current stack: R Q P Reversed stack: P Q R