基于java的栈实现

博客介绍了栈的两种实现方式。基于数组的顺序栈,指定初始容量后扩容需新建数组并复制原数据;基于链表的链式栈,理论上容量无上限。还给出了链式栈的反向生成链结构实现,且使用同步机制保证多线程环境出入栈安全。

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

栈可基于数组和链表来实现,基于数组的栈被称为顺序栈,栈的容量指定初始大小之后不可扩容,扩容需要传新建新数组,将原数组copy过来,

基于链表实现的栈成为链式栈,容量理论上无上限,以下分别实现

顺序栈

public class ArrayStack {

    int[] stack;

    public int top;

    public ArrayStack(int size) {
        this.stack = new int[size];
    }

    public boolean push(int val) {
        if(top >= stack.length) {
            return false;
        }
        stack[top++] = val;
        return true;
    }

    public int pop() {
        if(top == 0) {
            return throw new IndexOutOfBoundsException();
        }
        return stack[--top];
    }
    //验证
    public static void main(String[] args) {
        stack.push(10);
        stack.push(11);
        stack.push(12);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}

链式栈:这里使用的是反向生成链结构,push时从头部插入节点,pop时从头发弹出节点。下例使用了同步机制,保证在多线程环境出入栈的安全性

public class LinkedStack {
    class Node{
        private String value;

        private Node pre;

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

        public String getValue() {
            return value;
        }
    }
    // 记录栈的长度
    public int length;
    // 顶部栈针
    private Node top;

    public boolean push(String value) {
        synchronized (this) {
            if (top == null) {
                Node node = new Node(value);
                top = node;
                incrLength();
                return true;
            }
            Node t = new Node(value);
            t.pre = top;
            top = t;
            incrLength();
        }
        return true;
    }

    public String pop() {
        if(top == null) {
            return null;
        }
        String result = null;
        synchronized (this) {
            Node returnNode = top;
            top = top.pre;
            decLength();
            result = returnNode.getValue();
        }
        return result;
    }

    private synchronized void incrLength() {
        length++;
    }
    private synchronized void decLength() {
        length--;
    }

    public static void main(String[] args) throws InterruptedException {
        LinkedStack stack = new LinkedStack();
        stack.push("a");
        stack.push("b");
        stack.push("c");
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.length);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值