我们使用LinkedList可以很容易模拟出栈,现在我们使用泛型来实现栈,模拟内部链式存储机制
public class LinkedStack<T> {
//定义一个内部类
private static class Node<U>{
U item;
Node<U> next;
Node(){
item = null;
next = null;
}
Node(U item,Node<U> next){
this.item = item;
this.next = next;
}
boolean end() {
return item == null && next ==null;
}
}
//这是一个末端哨兵,用来判断栈是否为空
private Node<T> top = new Node<>();
//push方法就是模拟进栈操作,会创建一个新的对象,把它链接到前一个对象上。
public void push(T item) {
top = new Node<T>(item,top);
}
//模拟弹栈操作
public T pop() {
T result = top.item;
if(!top.end()) {
top = top.next;
}
return result;
}
public static void main(String[] args) {
String[] s = {"a","b","c","d"};
LinkedStack<String> li = new LinkedStack<String>();
for(String i : s) {
li.push(i);
}
String s1;
while((s1 = li.pop()) != null) {
System.out.println(s1);
}
}
}