创建Stack栈(Java、c#)

本文介绍了如何在C#中实现一个简单的栈数据结构,包括StackNode类的创建、Stack类的Push、Pop、Peek方法,以及在程序入口处的操作示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、创建stack节点类

namespace Testmain
{
    public class StackNode
    {
        public int Data;
        public StackNode? nextStack;
        public StackNode(int data)
        {
            this.Data = data;
            nextStack = null;
        }
    }
}

2、创建stack

namespace Testmain
{
    public class Stack
    {
        private StackNode? top;

        public void Push(int data)
        {
            StackNode newStack = new(data);
            if (top == null)
            {
                top = newStack;

            }
            else
            {
                newStack.nextStack = top;
                top = newStack;
            }
        }
        public int Pop()
        {
            if (top == null)
            {
                throw new Exception("The stack is empty");
            }
            int data = top.Data;
            top = top.nextStack;
            return data;
        }
        public int Peek()
        {
            if (top == null)
            {
                throw new InvalidOperationException("Stack is empty");
            }

            return top.Data;
        }
    }
}

3、程序入口

using System;
namespace Testmain
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Stack node = new Stack();
                node.Push(1);
                node.Push(2);
                node.Push(3);
                node.Push(4);
                node.Push(5);
                Console.WriteLine("The Stack top is:" + node.Peek());
                Console.WriteLine("The Stack pop is:" + node.Pop());
                Console.WriteLine("The Stack top is:" + node.Pop());
                Console.WriteLine("The Stack top is:" + node.Pop());
                Console.WriteLine("The Stack top is:" + node.Pop());
                Console.WriteLine("The Stack top is:" + node.Pop());
                Console.WriteLine("The Stack top is:" + node.Pop());

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值