使用 C# 反轉一個堆疊
建立一個堆疊,並向其中新增元素。
Stack st = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R');現在建立另一個堆疊,以便反轉此堆疊。
Stack rev = new Stack();
在該堆疊的計數不等於 0 之前,使用“入棧”和“出棧”方法進行反轉。
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
廣告
資料結構
聯網
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP