使用 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

更新日期: 22-Jun-2020

3K+ 浏览次数

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.