完整的MyStack類
/**
* Created by FireFlies on 2018/4/3.
*clearStack(): 將棧清空镀首。
*isStackEmpty(): 若棧為空肝谭, 返回true演怎, 否則返回false秧倾。
*getTop(): 若棧存在且非空嫂丙, 用e返回S的棧頂元素。
*push(E e): 若棧存在朦佩, 插入新元素e到棧S中并成為棧頂元素捺萌。
*pop(): 刪除棧中棧頂元素, 并用e返回其值新博。
*stackLength(): 返回棧的元素個數(shù)薪夕。
*/
public class MyStack<E> {
Object[] data = null;
int capacity;
int current;
public MyStack(){
this(10);
}
public MyStack(int initialSize){
data = new Object[initialSize];
capacity = initialSize;
current = 0;
}
/**
*進(jìn)棧操作push
* 類似于順序表的add操作,在尾部加入元素
*/
public boolean push(E e){
ensureSize();
data[current++] = e;
return true;
}
/**
* 出棧操作pop
* 刪除尾部元素
*/
public E pop(){
if(current<=0)
throw new RuntimeException("棧為空");
return (E) data[--current];
}
/**
* 若棧存在且非空叭披, 用e返回棧頂元素寥殖。
*/
public E getTop(){
if(current==0)
throw new RuntimeException("棧為空");
return (E) data[current-1];
}
/**
* 返回棧的元素個數(shù)。
* @return
*/
public int stackLength() {
return this.current;
}
/**
* 若棧為空涩蜘, 返回true嚼贡, 否則返回false。
*/
public boolean isStackEmpty(){
if(current=0)
return true;
return false;
}
/**
* 將棧清空同诫。
*/
public boolean clearStack(){
current = 0;
return true;
}
/**
* 獲取指定index的元素
* @return
*/
public E get(int index) {
validateIndex(index);
return (E) data[index];
}
/**
* 驗(yàn)證當(dāng)前下標(biāo)是否合法粤策,如果不合法,拋出運(yùn)行時異常
* @param index 下標(biāo)
*/
private void validateIndex(int index) {
if (index < 0 || index > current) {
throw new RuntimeException("數(shù)組index錯誤:" + index);
}
}
/**
* 實(shí)現(xiàn)數(shù)組動態(tài)擴(kuò)容
*/
public void ensureSize(){
if(current == capacity){
capacity *= 2;
Object[] temp = new Object[capacity];
for(int i=0; i<current; i++){
temp[i] = data[i];
}
data = temp;
}
}
/**
* 輸出當(dāng)前線性表所有元素
*/
public void print(){
System.out.print("[");
for(int i=0;i<this.stackLength();i++){
System.out.print(this.get(i)+" ");
}
System.out.println("]");
}
}
測試類
/**
* Created by FireFlies on 2018/4/3.
*/
public class MyStackTest {
public static void main(String[] args) {
MyStack myStack = new MyStack(3);
//測試進(jìn)棧操作
System.out.println("測試進(jìn)棧操作:");
myStack.push(new Integer(1));
myStack.push(new Integer(2));
myStack.push(new Integer(3));
myStack.print();
//測試getTop
System.out.println("查看棧頂元素");
System.out.println("Stack top: "+myStack.getTop().toString());
//測試出棧操作
System.out.println("測試出棧操作:");
System.out.println("出棧元素:"+myStack.pop().toString());
myStack.print();
System.out.println("出棧元素:"+myStack.pop().toString());
myStack.print();
//測試清空操作
System.out.println("測試清空操作");
myStack.clearStack();
System.out.println("Stack empty: "+myStack.isStackEmpty());
}
}
輸出結(jié)果
image.png