哎,上週還是沒有堅持寫博客,也許可能是因爲聚會吧和實習的緣故吧,但這些都不是理由,現在到中科院了,時間就很充分了,以後每週堅持至少寫3篇。廢話少說,今天開始學基本數據結構,第一講棧!
棧:作爲一種數據結構,是一種只能在一端進行插入和刪除操作的特殊線性表。它按照先進後出的原則存儲數據,先進入的數據被壓入棧底,最後的數據在棧頂,需要讀數據的時候從棧頂開始彈出數據(最後一個數據被第一個讀出來)。棧具有記憶作用,對棧的插入與刪除操作中,不需要改變棧底指針。
<pre name="code" class="java">package com.tangbo;
import java.lang.reflect.Array;
public class Stack<T> {
private int top;
private int length;
T [] stack;//聲明一個棧
@SuppressWarnings("unchecked")
public Stack(int length) {
this.length = length;
this.stack = (T[])Array.newInstance(Object.class,length);//不能用 stack = new T[length]初始化,當實現一個泛型類時,您可能想要構造一個數組T[]。因爲泛型是通過擦除(erasure)實現的,所以這是不允許的。//您可以嘗試把Object[]強制轉換爲T[]。但這是不安全的。具體化解決方案按照泛型教程的慣例,解決方案使用的是“類型令牌”,通過向構造函數添加一個Class<T>參數,可以強制客戶端爲類的類型參數提供正確的類對象。詳見:http://www.cnblogs.com/Fskjb/archive/2009/08/23/1552506.html
this.top = -1;//初始化棧頂
}
public boolean stackEmpty() {//判斷棧是否滿
boolean isEmpty = false;
if(top==-1)
{
isEmpty = true;
}
return isEmpty;
}
public boolean statckFull()//判斷棧是否爲空
{
boolean isFull = false;
if((top+1)==length)
{
isFull = true;
}
return isFull;
}
public void push(T t) {//入棧
if(statckFull())
{
System.err.print("棧滿了!");
}else
{
top++;
stack[top] = t;
}
}
public T pop() {//出棧
T t=null;
if(stackEmpty())
{
System.err.print("棧爲空!");
}else
{
t = stack[top];
top--;
}
return t;
}
public int stackLength() {//返回棧的長度
return top+1;
}
}
測試類:
package com.tangbo;
public class Test {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>(2);
stack.push(2);
stack.push(3);
int length = stack.stackLength();
for(int i=0;i<length;i++)
{
System.out.println("i="+i+":"+stack.pop());
}
}
}
源碼下載地址:http://pan.baidu.com/s/1mgqna3m