1. 程式人生 > >初始資料結構——鏈棧

初始資料結構——鏈棧

很多時候我們很難準確地估計所需棧的空間大小,就會造成棧溢位或者棧空間浪費的問題,
要避免這些問題,更好的方法就是使用鏈式儲存結構

public class LinkedStack
{
	private class Stack{
		Object data;
		Stack next;
		Stack(){
			next = null;
		}
	}
	Stack top = new Stack();
	
	//判空棧
	public boolean isEmpty() {
		if(top.next == null)return true;
		return false;
	}
	//入棧
	public boolean push(Object data) {
		Stack p = new Stack();
		p.data = data;
		p.next = top.next;
		top.next = p;
		return true;
	}
	//出棧
	public boolean pop() {
		if(isEmpty() == true) return false; //棧空不能出棧
		else {
			top.next = top.next.next;
			return true;
		}
	}
	//取棧頂元素
	public Object getTop() {
		if(isEmpty() == true) return 0;
		else {
			return top.next.data;
		}
	}
}