使用 C# 反转栈


设置一个栈并向其中添加元素。

Stack st = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R');

现在再设置另一个 stack 来反转它。

Stack rev = new Stack();

Until 栈的计数不等于 0,使用 Push 和 Pop 方法来反转它。

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.