Java Abstract Data Type Series: SimpleStack
November 27th, 2008 at 3:18pm |
Today I made a simple stack for you. It’s pretty much as basic as it gets. You push elements, you pop elements, you peek at elements, you get the size of the elements.
Here’s the code:
Node.java:
1 2 3 4 5 6 7 8 9 10 | public class Node<E> { private E content; private Node<E> below; public Node(E content) { this.content = content; } public E getContent() { return content; } public void setContent(E content) { this.content = content;} public Node<E> getBelow() { return below; } public void setBelow(Node<E> below) { this.below = below;} } |
SimpleStack.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /** * Simple stack. * @author Tobias Rusås Olsen * * @param <E> */ public class SimpleStack<E> { private Node<E> topNode; private int size; /** * Default constructor, sets the size of the stack to zero. */ public SimpleStack() { size = 0; } /** * Push element to the stack * @param content * @return */ public boolean push(E content) { if(size!=0) { Node<E> newNode = new Node<E>(content); newNode.setBelow(topNode); topNode = newNode; } else topNode = new Node<E>(content); size++; return true; } /** * Get element from the stack. * @return */ public E pop() { if(size==0) return null; Node<E> returnNode = topNode; topNode = returnNode.getBelow(); size--; return returnNode.getContent(); } /** * Look at top element of stack. * @return */ public E peek() { if(size==0) return null; return topNode.getContent(); } public int size() { return size; } } |