使用C#反转堆栈
设置堆栈并向其中添加元素。
Stack st = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R');现在设置另一个堆栈来反转它。
Stack rev = new Stack();
在堆栈计数不等于0之前,请使用PushandPop方法将其反转。
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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短