1. 程式人生 > >資料結構 - 棧

資料結構 - 棧

package com.test.testStack;

import java.util.Arrays;

public class TestStack {

    private Object[] array; // 模擬棧
    private int capacity;    // 棧的容量
    private int top;    // 棧頂元素的下標

    public TestStack() {
        this.capacity= 10;
        this.array = new Object[10];
        top = -1;
    }

    public TestStack(int capacity) {
        if (maxSize <= 0)
            throw new IllegalArgumentException("Illegal Argument");
        this.capacity= capacity;
        array = new Object[capacity];
        top = -1;
    }

    /**
     * 入棧
     * @param value 新加入到棧頂的元素值
     */
    private void push(Object elem) {
        enlarge(top + 1);
        array[++top] = elem;
    }

    /**
     * 出棧
     * @return 從棧頂出棧的元素值
     */
    private Object pop() {
        Object obj = null;
        if (top > 0) {
            obj = array[top];
            array[top--] = null;
            return obj;
        }
        else if (top == 0) {
            obj = array[top];
            top = -1;
            return obj;
        }
        return obj;
    }

    /**
     * 檢視棧頂元素的值
     * @return 棧頂元素的值
     */
    private Object peek() {
        return array[top];
    }

    /**
     * 判斷棧是否為空
     * @return 是否為空
     */
    private boolean isEmpty() {
        return top == -1;
    }

    /**
     * 判斷棧是否為滿
     * @return 是否為滿
     */
    private boolean isFull() {
        return top == (maxSize - 1);
    }

    /**
     * 判斷棧是否需要擴容
     * @param capacity 新容量
     * @return 是否需要擴容
     */
    public boolean enlarge(int newCapacity) {
		if (newCapacity >= capacity) {
			boolean flag = (capacity << 1) > Integer.MAX_VALUE;
			capacity = flag ? Integer.MAX_VALUE : capacity << 1;
			array = Arrays.copyOfRange(array, 0, capacity);
			return true;
		}
		return false;
	}

    public static void main(String[] args) {
        TestStack demo = new TestStack(3);
        demo.push(1);
        demo.push(2);
        demo.push(3);
        demo.push(4);
        System.out.println(demo.isFull());
        demo.pop();
        demo.pop();
        System.out.println(demo.array.length);
        System.out.println(demo.peek());
        demo.pop();
        System.out.println(demo.isEmpty());
    }



}