1. 定義
棧(stack),是一種線性存儲(chǔ)結(jié)構(gòu),它有以下幾個(gè)特點(diǎn):
- 棧中數(shù)據(jù)是按照"后進(jìn)先出(LIFO, Last In First Out)"方式進(jìn)出棧的。
- 向棧中添加/刪除數(shù)據(jù)時(shí),只能從棧頂進(jìn)行操作。
棧通常包括的三種操作:push、peek、pop。
- push -- 向棧中添加元素。
- peek -- 返回棧頂元素。
- pop -- 返回并刪除棧頂元素的操作。
2. 簡(jiǎn)單實(shí)現(xiàn)
public class GeneralArrayStack<T> {
private static final int DEFAULT_SIZE = 12;
private T[] mArray;
private int count;
public GeneralArrayStack(Class<T> type) {
this(type, DEFAULT_SIZE);
}
public GeneralArrayStack(Class<T> type, int size) {
// 不能直接使用mArray = new T[DEFAULT_SIZE];
mArray = (T[]) Array.newInstance(type, size);
count = 0;
}
// 將val添加到棧中
public void push(T val) {
mArray[count++] = val;
}
// 返回“棧頂元素值”
public T peek() {
return mArray[count - 1];
}
// 返回“棧頂元素值”,并刪除“棧頂元素”
public T pop() {
T ret = mArray[count - 1];
mArray[count - 1] = null; /* to let gc do its work */
count--;
return ret;
}
// 返回“棧”的大小
public int size() {
return count;
}
// 返回“?!笔欠駷榭? public boolean isEmpty() {
return size() == 0;
}
// 打印“?!? public void printArrayStack() {
if (isEmpty()) {
System.out.printf("stack is Empty\n");
}
System.out.printf("stack size()=%d\n", size());
int i = size() - 1;
while (i >= 0) {
System.out.println(mArray[i]);
i--;
}
}
}
測(cè)試:
public static void main(String[] args) {
GeneralArrayStack<String> stack = new GeneralArrayStack<>(String.class, 5);
for (int i = 0; i < 5; i++) {
stack.push("this is " + i);
}
System.out.println("棧頂:" + stack.peek());
String pop = stack.pop();
System.out.println("取出的棧頂元素:" + pop);
stack.printArrayStack();
}
結(jié)果:
棧頂:this is 4
取出的棧頂元素:this is 4
stack size()=4
this is 3
this is 2
this is 1
this is 0