Last active
December 29, 2015 12:19
-
-
Save rshepherd/7669957 to your computer and use it in GitHub Desktop.
A linked list-based implementation of a stack.
This file contains hidden or 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
public class ListBasedStack<T> implements Stack<T> | |
{ | |
private Node<T> top = null; | |
public boolean isEmpty() | |
{ | |
return top == null; | |
} | |
public void clear() | |
{ | |
top = null; | |
} | |
public void push(T data) | |
{ | |
top = new Node<T>(data, top); | |
} | |
public T pop() | |
{ | |
if(isEmpty()) { | |
throw new IllegalStateException("Stack is empty"); | |
} | |
T data = top.data; | |
top = top.next; | |
return data; | |
} | |
public T peek() | |
{ | |
if(isEmpty()) { | |
throw new IllegalStateException("Stack is empty"); | |
} | |
return top.data; | |
} | |
private static class Node<T> | |
{ | |
public T data; | |
public Node<T> next; | |
public Node(T data) | |
{ | |
this(data, null); | |
} | |
public Node(T data, Node<T> n) | |
{ | |
this.data = data; | |
next = n; | |
} | |
} | |
public interface Stack<T> { | |
/** | |
* Puts an element on the top of the stack | |
*/ | |
public void push(T data); | |
/** | |
* Takes the top element off of the stack | |
*/ | |
public T pop(); | |
/** | |
* Takes the top element off of the stack without actually removing it | |
*/ | |
public T peek(); | |
public boolean isEmpty(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment