1. 程式人生 > >資料結構複習之【棧】

資料結構複習之【棧】

棧:先進後出的線性表;

棧也可以通過順序儲存和鏈式儲存的方式實現;

一、順序儲存實現

陣列的尾端作為棧頂;

程式碼實現:

package org.xiazdong.list;

public class MyArrayStack<T> {
	private static final int DEFAULT_LENGTH = 10;
	private T[]t;
	private int length;
	private int top;
	public MyArrayStack(){
		t = (T[])new Object[DEFAULT_LENGTH];
		length = 0;
		top = -1;
	}
	public void push(T e){
		if((top+1)>=t.length){
			larger(t.length*2);
		}
		top++;
		if(top>=t.length){
			
		}
		t[top]=e;
	}
	public T top(){
		return t[top];
	}
	public T pop(){
		if(top<0){
			throw new ArrayIndexOutOfBoundsException();
		}
		T tmp = t[top];
		top--;
		return tmp;
	}
	public int getSize(){
		return top+1;
	}
	private void larger(int len){
		T[]tmp = (T[])new Object[len];
		for(int i=0;i<t.length;i++){
			tmp[i] = t[i];
		}
		t = tmp;
	}
	
}


二、鏈式儲存實現

連結串列的頭端作為棧頂;

程式碼實現如下:

package org.xiazdong.list;

import org.xiazdong.list.MyLinkedList.Node;

public class MyLinkedStack <T>{
	private Node top;
	private int count;
	public MyLinkedStack(){
		count = 0;
		top = null;
	}
	public T pop(){
		if(top==null){
			throw new ArrayIndexOutOfBoundsException();
		}
		T elem = top.elem;
		top = top.next;
		return elem;
	}
	
	public T top(){
		return top.elem;
	}
	public void push(T e){
		Node n = new Node();
		n.elem = e;
		n.next = top;
		top = n;
	}
	class Node{
		private T elem;
		Node next;
		public Node(){
			elem = null;
			next = null;
		}
		public Node(T elem,Node next){
			this.elem = elem;
			this.next = next;
		}
		
	}
}


三、比較

順序儲存 鏈式儲存
優點 訪問快、增加刪除都為O(1) 增加刪除都為O(1),對於空間沒有限制
缺點 浪費空間,容易溢位 指標需要空間

四、棧的應用

1.遞迴

我們這裡以斐波那契數為例;fib(n) = fib(n-1)+fib(n-2),fib(2) = fib(1) = 1;

遞迴和棧是密不可分的,遞迴的實現就是通過棧來完成的;


2.字尾表示式

我們在做計算器應用時肯定會用到字尾表示式,中綴表示式轉換到字尾表示式,字尾表示式求出值都是通過棧實現的;