单链表模仿栈

该篇博客详细介绍了如何使用链表模仿栈这一数据结构,重点在于栈的先进后出特性。通过定义Node类来创建链表节点,并在MyStack类中实现了push、pop、peek等基本操作。示例代码展示了如何初始化栈、压入元素、弹出元素以及查看栈顶元素的过程。

首先要明白栈有什么特色,毕竟知己知彼,百战不殆,那么栈有什么特色呢:先进后出


/**
 * 用链表模仿栈
 */
public class Code02 {

    public static class Node{
        private Integer value;
        private Node next;

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

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }

    public static class MyStack {
        private Integer size;
        private Node head;
        private Node tail;
        public MyStack() {
            size = 0;
        }

        public MyStack(Integer size) {
            this.size = size;
        }

        public boolean isEmpty(){
            return size==0;
        }

        public Node push(Integer value){
            Node add = new Node(value);
            if(size == 0){
                head = add;
                tail = add;
            } else {
                Node next = head;
                head = add;
                head.next = next;
            }
            size++;
            return head;
        }

        public Integer pop(){
            if(isEmpty()){
                return null;
            }
            Integer value = head.value;
            head = head.next;
            size--;
            return value;
        }

        public Integer peek(){
            if(isEmpty()){
                return null;
            }
            return  head.value;
        }

    }

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

        System.out.println(stack.peek());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());

    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值