public class MyStack {
private Object[] stack;
private int size;//元素的个数
//初始化数组的大小
public MyStack(int length){
stack=new Object[length];
}
//元素的个数
public int size(){
return size;
}
//动态扩展数组
public void ensureCapacity(){
if(size()==stack.length){
Object[] newStack=new Object[size()*3/2+1];
System.arraycopy(stack,0,newStack,0,size());
stack=newStack;
}
}
//判断栈是否已满
public boolean isFull(){
return size>=stack.length;
}
//判断栈是否为空
public boolean isEmpty(){
return size==0;
}
//入栈
public void push(Object obj){
size++;
ensureCapacity();
stack[size-1]=obj;
}
//出栈
public Object pop(){
Object obj=stack[--size];
stack[size]=null;
return obj;
}
public static void main(String[] args) {
MyStack myStack=new MyStack(4);
String[] s={"a","b","c","d"};
for (int i = 0; i <4; i++) {
myStack.push(s[i]);
}
while(!myStack.isEmpty()){
System.out.print(myStack.pop()+" ");
}
}
}
使用一个数组实现栈
最新推荐文章于 2022-10-23 10:40:29 发布