1. 程式人生 > >《java常用演算法手冊》 第二章 資料結構 棧 佇列

《java常用演算法手冊》 第二章 資料結構 棧 佇列

 順序棧的實現:

package LineStructure;
//參考 https://blog.csdn.net/icarus_wang/article/details/79561863

public class Stack<T> extends Object{
	
	int MaxLength = 10;
	
	T[] Array;
	
	int top = -1;//棧頂 初始為-1
	
	//預設構造
	public Stack(){
		this.MaxLength = MaxLength;
		this.Array = (T[]) new Object[MaxLength];//初始化陣列
		this.top = -1;
	}
	
	//長度構造
	public Stack(int maxLength){
		this.MaxLength = maxLength;
		this.Array = (T[]) new Object[MaxLength];
		this.top = -1;
	}
	
	//push value
	public void push(T value) {
		
		this.Array[++top] = value;
	}
	
	//pop
	public T pop() {
		
		T result = Array[top];
		Array[top] = null;
		top--;
		return result;
		
	}
	
	//length
	public int getLength() {
		return this.top+1;
	}
	
	//getTop
	public T getTop() {
		return Array[top];
	}
	
	public Boolean isFull() {
		if (top == MaxLength) {
			return true;
		}else {
			return false;
		}
	}
}