Java链表实现栈

栈的介绍,使用场景及数组实现,请看这篇文章。
栈的介绍,使用场景及数组实现

package cn.chmcyz.linkedstack;

/**
 * @author 谌涣谋
 * @date 2020/5/17 - 0:08
 */
public class LinkedStackDemo {
    public static void main(String[] args) {
        LinkedStack stack=new LinkedStack();
        stack.push(new Node(1));
        stack.push(new Node(2));
        stack.push(new Node(3));
        stack.push(new Node(4));
        stack.push(new Node(5));
        stack.show();
        System.out.println(stack.pop()+"出栈");
        System.out.println("======================");
        stack.show();
        System.out.println("栈顶的值为"+stack.peek());
        System.out.println("======================");
        stack.show();

    }

}

class LinkedStack{
    Node top=new Node(-1);
	//遍历栈
    public void show(){
        Node temp=top;
        while (temp.next!=null){
            System.out.println(temp);
            temp=temp.next;
        }
        System.out.println("================================");
    }
	//压栈

    public void push(Node node){
        node.next=top;
        top=node;
    }
	//出栈
    public Node pop(){
        Node temp=top;
        top=top.next;
        return  temp;
    }
	//取栈顶元素
    public Node peek(){

        return  top;
    }
}

class  Node{
    int number;
    Node next;

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值