使用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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿