简单模拟实现栈(Stack)结构,出栈(pop),入栈(push),查看栈顶元素(peek)....
import java.util.Arrays;
public class MyStack {
int[] elementData;
int usedSize;
//构造方法
public MyStack() {
this.elementData = new int[5];
this.usedSize = 0;//既代表有效长度,又代表当前位置可存放元素
}
//入栈
public void push(int data) {
//判满,扩容
if (isFull()) {
this.elementData = Arrays.copyOf(this.elementData , 2*this.elementData.length);
}
this.elementData[usedSize] = data;
this.usedSize++;//长度加1
}
//出栈
public int pop() {
//栈空
if(empty()){
throw new RuntimeException("栈空,无法出栈");//应该自己写个异常类
}
this.usedSize--;
int ret = elementData[usedSize];
//elementData[usedSize] = null;如果是引用类型的话
return ret;
}
//获取顶部元素
public int peek() {
//栈空
if(empty()){
throw new RuntimeException("栈空,无法查看栈顶元素");
}
return this.elementData[this.usedSize - 1];
}
//判空
public boolean empty() {
if (this.usedSize == 0)
return true;
return false;
}
//判空2
public boolean empty2(){
return this.usedSize == 0;
}
//计算长度
public int size() {
return this.usedSize;
}
//判满
public boolean isFull(){
if(this.usedSize == this.elementData.length)
return true;
return false;
}
//判满2
public boolean isFull2(){
return this.usedSize == this.elementData.length;
}
}