【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
import java.util.Iterator;
public class LinkedStack<U> {
private class Node<T> {
T data;
Node<T> next;
Node() {
data = null;
next = null;
}
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
boolean end() {
return data == null && next == null;
}
}
private Node<U> top = new Node<U>();
public U pop() {
U result = top.data;
if (!top.end())
top = top.next;
return result;
}
public void push(U data) {
top = new Node<U>(data, top);
}
public Iterator<U> iterator() {
return new Iterator<U>() {
public boolean hasNext() {
return !top.end();
}
public U next() {
return pop();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
LinkedStack<Integer> test = new LinkedStack<Integer>();
for (int i=0; i<10; i++)
test.push(i);
Iterator<Integer> it = test.iterator();
while (it.hasNext())
System.out.println(it.next());
}
}
没事,写着玩呢!呵呵!
来源:oschina
链接:https://my.oschina.net/u/229978/blog/64681