Skip to content

Instantly share code, notes, and snippets.

@cip123
Created July 16, 2012 18:07
Show Gist options
  • Save cip123/3124072 to your computer and use it in GitHub Desktop.
Save cip123/3124072 to your computer and use it in GitHub Desktop.
1.2 Pushdown stack (linked-list implementation)
package containers;
import java.util.Iterator;
public class Stack<T> implements Iterable<T>{
private Node first;
private int size;
private class Node {
T item;
Node next;
}
public boolean isEmpty(){
return first == null;
}
public int size() {
return size;
}
public void push(T item){
Node oldFirst = this.first;
first = new Node();
first.item = item;
first.next = oldFirst;
size++;
}
public T pop() {
T result = first.item;
first = first.next;
size--;
return result;
}
public Iterator<T> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator<T> implements Iterator<T> {
private int index = size;
public boolean hasNext() {
return index>0;
}
public T next() {
return (T) items[--index];
}
public void remove() {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment