使用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 哈尼族祝福语简短
10 恭喜生孩子祝福语简短
11 新年祝福语简短搞笑创意
12 初三新年祝福语简短
13 企业新春祝福语简短大全
14 买车新年祝福语简短创意
15 要庆祝生日祝福语简短
16 回复姐姐生日祝福语简短
17 老师结婚祝福语评论简短
18 喝酒祝福语大全简短新颖