Humboldt-Universität zu Berlin - Mathematisch-Naturwissenschaftliche Fakultät - Algorithm Engineering

IntStack.java

text/x-java IntStack.java — 2.7 KB

Dateiinhalt

import java.util.EmptyStackException;

/**
 * A data structure for storing integer values in last-in first-out (LIFO) manner.
 */
public class IntStack {

	private Element top;

	/**
	 * A constructor for creating an empty stack.
	 */
	public IntStack() {
		top = null;
	}

	/**
	 * Removes and returns the top integer value stored in the stack.
	 * 
	 * @return the top integer value of the stack
	 */
	public int pop() {
		if (top == null)
			throw new EmptyStackException();
		int value = top.getValue();
		top = top.getNext();
		return value;
	}

	/**
	 * Returns the top integer value stored in the stack without removing it.
	 * 
	 * @return the top integer value of the stack
	 */
	public int top() {
		if (top == null)
			throw new EmptyStackException();
		return top.getValue();
	}

	/**
	 * Tests whether the stack is empty.
	 * 
	 * @return true if the stack is empty, false otherwise
	 */
	public boolean isEmpty() {
		return top == null;
	}

	/**
	 * Puts a new integer value on top of the stack.
	 * 
	 * @param value
	 *            the integer value that is to be put on top of the stack
	 */
	public void push(int value) {
		Element newTop = new Element(value);
		newTop.setNext(top);
		top = newTop;
	}

	@Override
	public String toString() {
		Element runingElement = top;
		StringBuilder sb = new StringBuilder();
		while (runingElement != null) {
			sb.append(runingElement.getValue()).append("\n");
			runingElement = runingElement.getNext();
		}
		return sb.toString();
	}

	/**
	 * Duplicates the top integer value of the stack.
	 */
	public void dup() {
		// TODO: Code hier einfuegen.
	}

	/**
	 * Returns the number of elements in the stack.
	 * 
	 * @param value
	 *            the current size of the stack
	 */
	public int size() {
		// TODO: Code hier einfuegen.
	}

	/**
	 * Reverses the order of integer values in the stack.
	 */
	public void reverse() {
		// TODO: Code hier einfuegen.
	}

	/**
	 * Functions for testing methods {@link #dup() dup}, {@link #size() size}, and {@link #reverse() reverse}.
	 */
	public static void main(String[] args) {
		IntStack stack = new IntStack();

		int value = 7;
		System.out.println("Pushing " + value + ".");
		stack.push(value);
		System.out.println(stack.toString());

		value = 5;
		System.out.println("Pushing " + value + ".");
		stack.push(value);
		System.out.println(stack.toString());

		System.out.println("Duplicating top value.");
		stack.dup();
		System.out.println(stack.toString());

		value = 3;
		System.out.println("Printing size.");
		System.out.println(stack.size() + "\n");

		System.out.println("Reversing.");
		stack.reverse();
		System.out.println(stack.toString());

		System.out.println("Popping.");
		stack.pop();
		System.out.println(stack.toString());

		System.out.println("The result should be:\n5\n5");
	}

}