链表形式模拟栈的数据结构

我们用链表的形式来模拟栈的数据结构

分析:
1.入栈:可以链表节点的添加看作入栈的过程
2.出栈:我们从栈中每取出一个数据,就拿到链表的尾部的值并从将尾部的节点删除
3.显示栈中所有数据:链表反转输出

代码实现

1.定义节点

class Node {
    public int value;
    public Node next;

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

2.定义栈

class LinkedListStack {
    private Node head = new Node(0);
}

3.入栈(push)

  //向栈中放入数据
    public void push(Node node) {
        Node top = head;
        while (top.next != null) {
            top = top.next;
        }
        top.next = node;
    }

4.出栈(pop)获取链表的尾部的值并从将尾部的节点删除

  public int pop() throws Exception {
        Node pre=head;
        Node top = head.next;
        if (top==null){
            throw new Exception("栈空,无法取出数据");
        }
        while (top.next!=null){
            top=top.next;
            pre=pre.next;
            
        }
        int value=top.value;
        pre.next=null;
        
        return value;
    }
}

出栈图解(字丑请多担待!)

在这里插入图片描述
显示栈中所有数据(链表反转输出)

//先将单向链表原地反转
    public void show() {
        Node temp = head.next.next;
        if (head.next == null) {
            System.out.println("栈空,无法显示");
        }
        head.next.next=null;
        while (temp != null) {
            Node cur=temp.next;
            temp.next=head.next;
            head.next=temp;
            temp=cur;
        }
        //循环遍历输出值
       temp= head.next;
        while (temp!=null){
            System.out.println(temp.value);
            temp=temp.next;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值