📜  在C#中实现堆栈

📅  最后修改于: 2021-05-29 20:27:51             🧑  作者: Mango

堆栈是线性数据结构。它遵循LIFO(后进先出)模式进行输入/输出。在堆栈中执行以下三个基本操作:

  • 推送:在堆栈中添加一个项目。如果堆栈已满,则称其为堆栈溢出条件。
  • 弹出:从堆栈中删除一个项目。这些项目以推入的相反顺序弹出。如果堆栈为空,则称其为堆栈下溢条件。
  • 窥视:返回堆栈的最顶层元素。

下面给出的是使用数组实现堆栈的C#代码

using System;
  
namespace StackImplementation
{
    internal class Stack
    {
        static readonly int MAX = 1000;
        int top;
        int[] stack = new int[MAX];
  
        bool IsEmpty()
        {
            return (top < 0);
        }
        public Stack()
        {
            top = -1;
        }
        internal bool Push(int data)
        {
            if (top >= MAX)
            {
                Console.WriteLine("Stack Overflow");
                return false;
            }
            else
            {
                stack[++top] = data;
                return true;
            }
        }
  
        internal int Pop()
        {
            if (top < 0)
            {
                Console.WriteLine("Stack Underflow");
                return 0;
            }
            else
            {
                int value = stack[top--];
                return value;
            }
        }
  
        internal void Peek()
        {
            if (top < 0)
            {
                Console.WriteLine("Stack Underflow");
                return;
            }
            else
                Console.WriteLine("The topmost element of Stack is : {0}", stack[top]);
        }
  
        internal void PrintStack()
        {
            if (top < 0)
            {
                Console.WriteLine("Stack Underflow");
                return;
            }
            else
            {
                Console.WriteLine("Items in the Stack are :");
                for (int i = top; i >= 0; i--)
                {
                    Console.WriteLine(stack[i]);
                }
            }
        }
    }
  
    class Program
    {
        static void Main(string[] args)
        {
            Stack myStack = new Stack();
  
            myStack.Push(10);
            myStack.Push(20);
            myStack.Push(30);
            myStack.Push(40);
            myStack.PrintStack();
            myStack.Peek();
            Console.WriteLine("Item popped from Stack : {0}", myStack.Pop());
            myStack.PrintStack();
        }
    }
}

输出:

Items in the Stack are :
40
30
20
10
The topmost element of Stack is : 40
Item popped from Stack : 40
Items in the Stack are :
30
20
10