import java.util.Arrays;
public class MyStack {
public int[] elem;
public int usedSize;
public MyStack(){
this.elem=new int[5];
}
public void push(int val){
if(isFull()){
this.elem= Arrays.copyOf(this.elem,this.elem.length*2);
}
this.elem[this.usedSize]=val;
this.usedSize++;
}
public boolean isFull(){
return this.usedSize==this.elem.length;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
//法一:
int oldVal=this.elem[usedSize-1];
this.usedSize--;
return oldVal;
//法二:
//this.usedSize--;
//return this.elem[usedSize];
}
public boolean isEmpty(){
return this.usedSize==0;
}
public int peek(){
if(isEmpty()){
throw new RuntimeException("栈为空!");
}
return this.elem[usedSize-1];
}
public static void main(String[] args) {
MyStack stack=new MyStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
stack.push(6);
System.out.println(stack.pop());
System.out.println(stack.peek());
System.out.println(stack.peek());
System.out.println(stack.isEmpty());
}
}
用数组实现栈~
于 2022-01-23 00:46:01 首次发布