Created
July 16, 2012 18:07
-
-
Save cip123/3124072 to your computer and use it in GitHub Desktop.
1.2 Pushdown stack (linked-list implementation)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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