最近在看算法,看到了棧,就想著有一次面試時(shí)遇到了筆試題是,自己實(shí)現(xiàn)一個(gè)棧結(jié)構(gòu),當(dāng)時(shí)沒有寫出來,現(xiàn)在看到,就想著用數(shù)組實(shí)現(xiàn)一個(gè)簡單的順序棧。直接上代碼:
public class ArrayStack {
private String [] items; //數(shù)組
private int count; //棧中元素個(gè)數(shù)
private int n; //棧的大小
//初始化數(shù)組
public ArrayStack(int n) {
this.items = new String[n];
this.n = n;
this.count = 0;
}
//入棧操作
public boolean Push (String item) {
if (count == n) { //如果為n則棧滿了,入棧失敗
return false;
}
items[count] = item;//將item放到下標(biāo)為count的位置
count++; //并且count加一
return true;
}
//出棧操作
public String Pop () {
if (count == 0) { //如果為零,則棧中無數(shù)據(jù)
return null;
}
String temp = items[count-1]; //返回?cái)?shù)組中下標(biāo)為count—1的值
count--; //并且count減一
return temp;
}
}