import java.util.Iterator; public class LStack implements IStack { private Link top; public LStack() { top = null; } public void push(T newItem) { top = new Link(newItem, top); } public T peek() { if(isEmpty()) { throw new EmptyStackException(); } return top.getDatum(); } //return the evictee //remove its link from the top. public T pop() { if(isEmpty()) { throw new EmptyStackException(); } T out = top.getDatum(); top = top.getNext(); return out; } public boolean isEmpty() { return top == null; } public int size() { int count = 0; for(Link nav = top; nav != null; nav = nav.getNext()) { count++; } return count; } public void clear() { top = null; } @Override public String toString() { StringBuffer sb = new StringBuffer("["); for(Link nav = top; nav != null; nav = nav.getNext()) { sb.append(String.format("%s, ", nav.getDatum())); } sb.delete(sb.length() - 2, sb.length()); sb.append("]"); return sb.toString(); } public Iterator iterator() { return new Navigator(); } /*****************Alien*********************/ class Navigator implements Iterator { Link nav; public Navigator() { nav = top; } public void remove() { throw new UnsupportedOperationException(); } public boolean hasNext() { return nav != null; } public T next() { T out = nav.getDatum(); nav = nav.getNext(); return out; } } public static void main(String[] args) { IStack s = new LStack<>(); System.out.println(s.size() == 0); s.push("C"); s.push("B"); s.push("A"); System.out.println(s); System.out.println(s.size() == 3); for(String q:s) { System.out.println(q); } s.pop(); System.out.println(s); System.out.println(s.size() == 2); s.clear(); for(int k = 0; k <25000; k++) { s.push("" + k); } System.out.println(s.size() == 25000); /*for(String q:s) { System.out.println(q); }*/ for(int k = 0; k <25000; k++) { s.pop(); } System.out.println(s.isEmpty()); } } class Link { private final T datum; private Link next; public Link(T datum, Link next) { this.datum = datum; this.next = next; } public T getDatum() { return datum; } public Link getNext() { return next; } }