Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/9450676 to your computer and use it in GitHub Desktop.
Save jingz8804/9450676 to your computer and use it in GitHub Desktop.
A Stack using LinkedList
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedListStack<Item> implements Iterable<Item> {
private class Node {
Item value;
Node next;
}
private Node top;
private int count;
public LinkedListStack() {
top = null;
count = 0;
}
public boolean isEmpty() {
if (top == null)
return true;
return false;
}
public void push(Item val) {
Node n = new Node();
n.value = val;
n.next = top;
top = n;
count++;
}
public Item pop() throws Exception {
if (top == null)
throw new Exception("The stack is already empty");
Item val = top.value;
top = top.next;
count--;
return val;
}
public int size() {
return count;
}
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private Node current = top;
public boolean hasNext() {
return top != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext())
throw new NoSuchElementException();
Item item = current.value;
current = current.next;
return item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment