Life of the IT-Drummer

A web log from Tobias Rusås Olsen.

Java Abstract Data Type Series: SimpleStack

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;
	}
}
RSS 2.0 | Trackback | Comment

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">