单链表实现栈

public class StackDemo {

    public static void main(String[] args) {
        //链表模拟栈测试
        LinkedListStack stack = new LinkedListStack(3);
        try {
            stack.push(1);
            stack.push(2);
            stack.push(3);
            stack.push(4);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        stack.show();
        try {
            System.out.println("出栈:" + stack.pop());
            System.out.println("出栈:" + stack.pop());
            System.out.println("出栈:" + stack.pop());
            System.out.println("出栈:" + stack.pop());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        stack.show();
    }
}

class LinkedListStack {

    private int maxSize;
    private Node top;

    public LinkedListStack(int maxSize) {
        this.maxSize = maxSize;
        top = new Node(0);
        top.next = null;
    }

    public boolean isEmpty() {
        return top.next == null;
    }

    public boolean isFull() {
        return size() == maxSize;
    }

    public int size() {
        if (isEmpty()) {
            return 0;
        }
        Node cur = top;
        int count = 0;
        while (cur.next != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }

    /*
    头插入法
     */
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满~");
            return;
        }
        Node newNode = new Node(value);
        //如果栈中还没有元素
        if (isEmpty()) {
            top.next = newNode;
            return;
        }
        //如果栈中已经至少有一个元素,则把新添加的元素添加到链表头部
        newNode.next = top.next;
        top.next = newNode;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空~");
        }
        //获取该出栈元素的值
        int out = top.next.num;
        //把出栈的元素删除
        top.next = top.next.next;
        return out;
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("栈空~");
            return;
        }
        Node cur = top.next;
        int i = 0;
        while (cur != null) {
            System.out.printf("arrar[%d]=%d\n", size()-i, cur.num);
            i++;
            cur = cur.next;
        }
    }

}

class Node {
    public int num;
    public Node next;

    public Node(int num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "Node{" +
                "num=" + num +
                '}';
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值