算法---栈(java实现)

public class Stack {
    //定义一个头和一个当前节点
    public Node head;
    public Node current;

    //方法:入栈操作
    public void push(int data) {
    //如果当前栈为空,则新建一个节点保存数据,新建一个current节点指向当前节点
        if(head == null) {
            head = new Node(data);
            current = head;
        } else {
            Node nextNode = new Node(data);
            nextNode.pre = current; //上一个节点作为新建节点前驱节点
            current = nextNode;//前驱节点指向新建节点
        }
    }
    //方法出栈
    public Node pop() {
        if(current == null) {
            return null;
        }

        //
        Node node = current;
        //当前节点的前驱节点指向上一个节点的
        current = current.pre;
        return node;
    }

    class Node{
        int data;
        Node pre;

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

    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push(1);
        stack.push(2);
        stack.push(3);

        //输入current节点的数据
        System.out.println(stack.pop().data);
        System.out.println(stack.pop().data);
        System.out.println(stack.pop().data);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值