用java陣列實現棧
阿新 • • 發佈:2018-12-23
棧是一種常見的資料結構。如果用一句話來概括棧的特點,估計大部分同學都能脫口而出:後進先出,即先進來的元素儲存在棧的最底部,新來的元素則在棧頂堆積,直到棧滿為止;而取元素的時候,只能從棧頂取,直到棧空為止。整個過程,與摞書的過程很類似:放書的時候都是摞在最上面,取書的時候也是從最上面開始取。要想取出下面的書,就必須先將上面的書先取走。
原理就講這麼多,本身也比較簡單。接下來,照例是咱們的口號:
talk is cheap, show me the code
package leilei.bit.edu.stacktest;
/**
* @author lei.wang
*
*/
public class Stack {
//存資料的陣列
int[] data;
//棧的最大長度
private int size;
//棧頂的位置
private int top;
public Stack(int size) {
this.size = size;
data = new int[size];
top = -1;
}
public int getSize() {
return size;
}
public int getTop() {
return top;
}
/**
* 判斷是否為空棧
* @return
*/
public boolean isEmpty() {
return top == -1;
}
/**
* 判斷是否為滿棧
* @return
*/
public boolean isFull() {
return (top+1) == size;
}
/**
* 壓棧操作
* @param data
* @return
*/
public boolean push(int data) {
if(isFull()) {
System.out.println("the stack is full!");
return false;
} else {
top++;
this.data[top] = data;
return true;
}
}
/**
* 彈棧操作
* @return
* @throws Exception
*/
public int pop() throws Exception {
if(isEmpty()) {
throw new Exception("the stack is empty!");
} else {
return this.data[top--];
}
}
/**
* 獲取棧頂的元素,但不彈棧
* @return
*/
public int peek() {
return this.data[getTop()];
}
public static void main(String[] args) {
Stack stack = new Stack(20);
stack.push(0);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Now the top_num is:" + stack.peek());
while(! stack.isEmpty()) {
try {
System.out.println(stack.pop());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
程式碼執行結果
Now the top_num is:3
3
2
1
0
程式碼本身比較簡單,就不在過多解釋,如果還有不懂的地方請看註釋;註釋還不懂的話,請留言。