棧的實現(分別用數組和鏈表的java實現)


/**
 * 文件名:StackText.java
 * 時間:2014年10月21日下午8:43:02
 * 作者:修維康
 */
package chapter3;

/**
 * 類名:StackText 說明:用鏈表和數組分別實現棧;
 */
class ArrayStack<AnyType> {
	public static final int DEFAULT_CAPACITY = 10;
	private AnyType[] theArray;
	private int topOfStack;
	private int size;

	public ArrayStack() {
		clear();
		topOfStack = -1;
	}

	public void push(AnyType x) {
		if (size == theArray.length)
			ensureCapacity(2 * size + 1);
		theArray[++topOfStack] = x;
		size++;
	}

	public AnyType top() {
		if (topOfStack != -1)
			return theArray[topOfStack];
		return null;
	}

	public AnyType pop() {
		if (topOfStack != -1)
			size--;
		return theArray[topOfStack--];
	}

	public void clear() {
		topOfStack = -1;
		ensureCapacity(DEFAULT_CAPACITY);
	}

	public boolean isEmpty() {
		return topOfStack == -1;
	}

	public void ensureCapacity(int newCapacity) {
		if (newCapacity < size)
			return;
		AnyType[] old = theArray;
		theArray = (AnyType[]) new Object[newCapacity];
		for (int i = 0; i < size; i++)
			theArray[i] = old[i];
	}
}

/**
 * 類名:LinkedStack 說明:鏈表實現棧
 */
class LinkedStack<AnyType> {
	private static class Node<AnyType> {
		Node(AnyType data, Node<AnyType> prev) {
			this.data = data;
			this.prev = prev;
		}

		private AnyType data;
		private Node<AnyType> prev;
	}

	private Node<AnyType> bottom;

	public LinkedStack() {
		clear();
	}

	public void clear() {
		bottom = new Node<AnyType>(null, null);
	}

	public void push(AnyType x) {
		bottom = new Node<AnyType>(x, bottom);
	}

	public AnyType top() {
		if (bottom != null)
			return bottom.data;
		return null;
	}

	public AnyType pop() {
		if (bottom != null) {
			bottom = bottom.prev;
			return bottom.data;
		}
		return null;
	}

	public boolean isEmpty() {
		return bottom.prev == null;
	}
}

public class StackTest {

	/**
	 * 方法名:StackText.java 說明:測試
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ArrayStack stack1 = new ArrayStack();
		for (int i = 1; i < 100; i++)
			stack1.push(i);
		// stack1.clear();
		System.out.println(stack1.top());
		while (!stack1.isEmpty())
			System.out.println(stack1.pop());

		ArrayStack stack2 = new ArrayStack();
		stack2.push(1);
		stack2.push(2);
		stack2.push(3);
		stack2.push(4);
		// stack2.clear();
		System.out.println(stack2.top());
		while (!stack2.isEmpty())
			System.out.println(stack2.pop());
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章