package generic;
public class LinkedStack<T> {
private static class Node<U> {
U item;
Node<U> nextNode;
Node() {
item = null;
nextNode = null;
}
Node(U item, Node<U> nextNode) {
this.item = item;
this.nextNode = nextNode;
}
boolean end() {
return item == null && nextNode == 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.nextNode;
}
return result;
}
public static void main(String[] args) {
LinkedStack<String> str = new LinkedStack<String>();
for(String str1:"my name is eric".split(" ")){
str.push(str1);
}
String string;
while((string=str.pop())!=null){
System.out.println(string);
}
}
}
public class LinkedStack<T> {
private static class Node<U> {
U item;
Node<U> nextNode;
Node() {
item = null;
nextNode = null;
}
Node(U item, Node<U> nextNode) {
this.item = item;
this.nextNode = nextNode;
}
boolean end() {
return item == null && nextNode == 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.nextNode;
}
return result;
}
public static void main(String[] args) {
LinkedStack<String> str = new LinkedStack<String>();
for(String str1:"my name is eric".split(" ")){
str.push(str1);
}
String string;
while((string=str.pop())!=null){
System.out.println(string);
}
}
}
输出
eric
is
name
my