使用 C# 反转堆栈
csharpprogrammingserver side programming更新于 2025/9/23 23:52:17
设置一个堆栈并向其中添加元素。
Stack st = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R');
现在设置另一个堆栈来反转它。
Stack rev = new Stack();
直到此堆栈的计数不等于 0,使用 Push 和 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

