使用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 恩师诗词祝福语简短大全