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()); } }
沒事,寫着玩呢!呵呵! java