Last active
August 29, 2015 13:57
-
-
Save jingz8804/9450676 to your computer and use it in GitHub Desktop.
A Stack using LinkedList
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
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