Java使用链表实现栈

链表实现栈

思路

  1. 创建一个链表head为链表的头
  2. 插入元素的时候
    1. 如果head==null,创建链表,head指向这个结点
    2. 如果head != null,利用方法getLast()得到最后一个结点last,然后last.next = 新的节点,新节点的下一个节点为null;
  3. 弹栈的时候
    1. 如果head==null,直接返回-1
    2. 如果head != null,得到倒数第二个元素lastLast,lastLast.next=null;
      1. 在得到倒数第二个元素lastLast的时候,先要获得倒数第一个元素,这个元素的值是最后需要返回的,在这种情况里面,last可能为null,这样的话最后返回的head就为null。
class Node {
    int value;
    Node next = null;
    Node(int value) {
        this.value = value;
    }
}
public class MyStack2 {
    private Node head = null;//链表
    //进栈
    public void push(int element) {
        if(head == null) {
            head = new Node(element);
        }else{
            Node last = getLast(head);
            last.next = new Node(element);
            last.next.next = null;
        }
    }

    private Node getLast(Node node) {
        if(node == null) {
            return null;
        }
        Node last = head;
        while(node.next != null) {
            last = last.next;
        }
        return last;
    }

    //出栈
    public int pop() {
        if(head == null) {
            return -1;
        }
        Node last = getLast(head);
        if(head.next == null) {
            head = null;
            return last.value;
        }

        Node lastlast = getLastLast(head);

        lastlast.next = null;
        return last.value;
    }

    private Node getLastLast(Node head) {
        if(head == null || head.next == null) {
            return null;
        }
        Node lastLast = head;
        while (lastLast.next.next != null) {
            lastLast = lastLast.next;
        }
        return lastLast;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值