1. 程式人生 > >Java實現---連結串列實現棧

Java實現---連結串列實現棧

 用連結串列實現棧:

其實就只是換了個名字,包裝起來而已,沒什麼新的東西。

注:這裡插入結點的方法應為在頭部插入結點(與輸入的值逆置),這樣構成的才是棧

/**
 * 用連結串列實現棧
 * @author Administrator
 *
 */
public class LinkStack {
	private LinkList theList;
	
	public LinkStack(){
		theList = new LinkList(); 
	}
	
	//入棧
	public void push(int data) {
		theList.Insert(data);
	}
	
	//出棧
	public int pop(){
		return theList.delete().data;
	}
	
	//檢查棧是否為空
	public boolean isEmpty() {
		return theList.isEmpty();
	}
	
	public void displayStack() {
		System.out.print("Stack (top--->bottom): ");
		theList.displayList();
	}
}
/**
 * 測試(連結串列)棧
 * @author Administrator
 *
 */
public class TestLinkStack {
	public static void main(String[] args) {
		LinkStack theStack = new LinkStack();
		theStack.push(20);
		theStack.push(40);
		
		theStack.displayStack();
		
		theStack.push(60);
		theStack.push(80);
		
		theStack.displayStack();
		
		theStack.pop();
		theStack.pop();
		
		theStack.displayStack();
	}
}

測試結果:

Stack (top--->bottom): {40} {20}  Stack (top--->bottom): {80} {60} {40} {20}  Stack (top--->bottom): {40} {20}