C#实现栈

栈的定义

栈(Stack)是只允许在一端进行插入或删除操作的线性表。

栈的示意图:
栈

  • 栈顶Top:线性表允许插入和删除的那一端。
  • 栈底Bottom:固定的,不允许进行插入和删除的另一端。

数组实现

public class ArrayStack<T>
{
    public T[] array;
    public int top;
    public int count;
    public int capacity => array == null ? 0 : array.Length;

    public ArrayStack(int capacity = 5)
    {
        array = new T[capacity];
        top = 0;
        count = 0;
    }

    public void Push(T value)
    {
        if (count >= capacity)
            Extend();
        array[top] = value;
        top++;
        count++;
    }

    public T Pop() 
    {
        if (count == 0)
            throw new Exception("Stack is empty");
        top--;
        T value = array[top];
        count--;
        return value;
    }

    public T Peek()
    {
        if (count == 0)
            throw new Exception("Stack is empty");
        return array[top - 1];
    }

    public void Extend()
    {
        int newCapacity = capacity * 2;
        T[] newArray = new T[newCapacity];
        for (int i = 0; i < top; i++)
            newArray[i] = array[i];
        array = newArray;
    }
}

注意:取栈顶元素时取地是top-1的值,不是top的值;

链表实现

public class Node<T>
{
    public T value { get; set; }
    public Node<T> next { get; set; }

    public Node() { }

    public Node(T value)
    {
        this.value = value;
    }
}



public class LinkListStack<T>
{
    public Node<T> top;
    public Node<T> bottom;
    public int count;

    public LinkListStack()
    {
        count = 0;
    }


    public void Push(T value)
    {
        Node<T> node = new Node<T>(value);
        node.next = top;
        top = node;
        count++;
    }

    public T Pop() 
    {
        if (count == 0)
            throw new Exception("Stack is empty");
        T value = top.value;
        top = top.next;
        count--;
        return value;
    }

    public T Peek()
    {
        if (count == 0)
            throw new Exception("Stack is empty");
        return top.value;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值