思路:
1、使用链表实现一个栈,便于扩容(不用考虑数组扩容场景),维护根节点和最后入栈的节点
2、节点中维护pre指针,便于pop()时快速找到上一个节点
代码:
package com.datastructure.stackqueue;
/**
* 实现一个栈,自定义栈,用链表实现,方便扩容
*/
public class DefineStack<T> {
private Node<T> root;
private Node<T> tail;
static class Node<T> {
T value;
Node<T> pre;
Node (T value) {
this.value = value;
}
@Override
public String toString() {
if (this.pre == null) {
return String.valueOf(this.value);
}
return this.pre.toString() + " <- " + this.value;
}
}
/**
* 有前驱指针的节点
*
* root <- tail
* root.pre = null
* tail.pre = root
*
*/
public T push(T t) {
if (root == null) {
root = new Node<T>(t);
tail = root;
return t;
}
Node<T> node = new Node<T>(t);
node.pre = tail;
tail = node;
return t;
}
public T pop() {
if (null == root) {
throw new RuntimeException("stack is empty");
}
T ret = null;
if (root == tail) {
ret = root.value;
root = null;
tail = null;
return ret;
}
ret = tail.value;
tail = tail.pre;
return ret;
}
@Override
public String toString() {
return tail.toString();
}
public static void main(String[] args) {
DefineStack<Integer> s = new DefineStack<>();
s.push(1);
s.push(2);
s.push(3);
s.pop();
s.push(4);
s.push(5);
s.pop();
System.out.println(s);
}
}
参考: