public class StackTest<T> {
public static class Node<U>{
public U item;
public Node next;
public Node() {
this.item = null;
this.next = null;
}
public Node(U item, Node<U> next) {
this.item = item;
this.next = next;
}
public boolean end() {
return item == null && next == null;
}
}
private Node<T> top = new Node<T>();
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) {
StackTest<String> st = new StackTest<>();
for (String str : "I love java".split(" ")) {
st.push(str);
}
while (!st.top.end()) {
System.out.println(st.pop());
}
}
}
使用java实现栈
最新推荐文章于 2024-07-06 13:29:45 发布