算法学习(4):栈的特点以及实现

这篇博客介绍了如何使用链表和数组这两种不同的数据结构来实现栈。栈是一种先进后出的数据结构,文中通过Java代码展示了如何创建并操作栈,包括push、pop和peek等基本操作。链表实现允许动态扩展,而数组实现则更适用于固定大小的需求,如果要支持动态大小,可以使用ArrayList替代数组。
摘要由CSDN通过智能技术生成

栈(stack)是一种逻辑数据结构,代表的是先进后出的区域.就比如栈是一个杯子(形状为圆形),杯口直径为10cm,然后这个数据就是略小与杯口的饼干形状与杯口相同,然后饼干放进去后每一次只能那一块,这个时候就只能拿到最上面也就是最后放进去的那块.

在这里插入图片描述

用链表自己实现一个栈

public class MyStack<E> {

    private Node<E> node;


    public MyStack() {
    }


    public E push(E item) {
        if (node == null) {
            this.node = new Node<>(item, null, null);
        } else {
            this.node = new Node<>(item, node, null);
//            Node previous = node.previous;
//            previous.next=node;
        }

        return item;
    }

    public synchronized E pop() {
        E obj = node.val;

        Node previous = node.previous;
        if (previous != null) {
            previous.next = null;
        }
        this.node = previous;
        return obj;
    }

    public synchronized E peek() {
        if (node == null)
            throw new EmptyStackException();


        E obj = node.val;
        return obj;
    }
}

用数组自己实现一个栈

public class MyArrayStack<E> {

    private Object[] array;
    private int index;



    public MyArrayStack(int size) {
        this.array =new Object[size];
    }

    public E push(E item) {

        if (index==array.length)
            throw new ArrayIndexOutOfBoundsException();

       array[index]=item;
       index++;

        return item;
    }

    public synchronized E pop() {
        if ( array[0] == null)
            throw new EmptyStackException();
        E obj = (E) array[index-1];

        array[index-1]=null;
        index--;

        return obj;
    }

    public synchronized E peek() {
        if ( array[0] == null)
            throw new EmptyStackException();


        E obj = (E) array[index-1];
        return obj;
    }

}

这里是用固定大小的数组实现的,如果要用动态数组的话,可以换成ArrayList替换array.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值