使用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 好听的元旦简短祝福语