接口:
interface IMyStack {
// 将 item 压入栈中
void push(int item);
// 返回栈顶元素,并且出栈
int pop();
// 返回栈顶元素,但不出栈
int peek();
// 判断这个栈是否为空栈
boolean empty();
// 返回元素个数
int size();
}
实现:
public class MyStackImpl implements IMyStack {
private int[] elem;//存放数据元素的数组
private int top;//存放数据元素的下标
private int usedSize;//有效下标
int size=10;
public MyStackImpl(){
this.elem=new int[size];
this.top=0;
}
private boolean isFull(){
return this.top==this.elem.length;
}
@Override
public void push(int item) {
if(isFull()){
throw new UnsupportedOperationException();
}
this.elem[this.top++]=item;
this.usedSize++;
}
@Override
public int pop() {
if(empty()){
throw new UnsupportedOperationException();
}else{
this.top--;
this.usedSize--;
return this.elem[this.top];
}
}