链表实现栈
思路:
- 创建一个链表head为链表的头
- 插入元素的时候
- 如果head==null,创建链表,head指向这个结点
- 如果head != null,利用方法getLast()得到最后一个结点last,然后last.next = 新的节点,新节点的下一个节点为null;
- 弹栈的时候
- 如果head==null,直接返回-1
- 如果head != null,得到倒数第二个元素lastLast,lastLast.next=null;
- 在得到倒数第二个元素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;
}
}