数据结构-栈

数据结构-栈

栈是一种操作受限的数据结构(后进先出)。
栈
栈的常见应用:

  1. 函数调用栈
  2. 编译器表达式求值
  3. 小、中、大括号是否匹配

栈用数组实现叫做顺序栈;栈用链表实现叫做链式栈。

顺序栈

	// 顺序栈 数组实现
    public class ArrayStack
    {
        private string[] arraystack;
        private int count; // 数组下标
        private int n; // 数组大小
        public ArrayStack(int N)
        {// 构造函数初始化数组大小
            arraystack = new string[N];
            n = N;
            count = 0;
        }
        // 入栈操作
        public bool push(string item)
        {
            if (count == n) return false;
            arraystack[count] = item;
            count++;
            return true;
        }
        // 出栈操作
        public string pop()
        {
            if (count == 0) return null;
            string item = arraystack[count-1];
            count--;
            return item;
        } 
    }
        static void Main(string[] args)
        {
            var arraystack = new ArrayStack(5);
            arraystack.push("one");
            arraystack.push("two");
            var item = arraystack.pop();
            Console.WriteLine(item);
            Console.ReadLine();
        }

在这里插入图片描述

链式栈

	// 链式栈 链表实现
    public class LinkedStack 
    { 
    	// 结点
        public class Node
        {
            public string Value { get; set; }
            public Node Next { get; set; }
            public Node(string value)
            {	
                Value = value;
            }
        }
        private Node first; // 链表头结点,也是栈顶指针
        // 入栈操作
        public void push(string item)
        {
            var newNode = new Node(item);
            newNode.Next = first;
            first = newNode;
        }
        // 出栈操作
        public string pop()
        {
            if (first == null) return null;
            var value = first.Value;
            return value; 
        }
    }
        static void Main(string[] args)
        {
            var linkedstack = new LinkedStack();
            linkedstack.push("three");
            linkedstack.push("four");
            var item = linkedstack.pop();
            Console.WriteLine(item);
            Console.ReadLine();
        }

链式栈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值