import java.util.Arrays;
//用数组实现栈
public class Stack {
private int[] array;
private int top;
public Stack(int defaultCapacity){
array = new int[defaultCapacity];
top = 0;
}
public Stack(){
this(20);
}
//入栈
public void push(int val){
if(top == array.length){
array = Arrays.copyOf(array,array.length * 2);
}
array[top++] = val;
}
//删除
public void pop(){
if(top <= 0){
System.out.println("栈为空,无法删除元素");
return;
}
top--;
array[top] = 0;//可有可无,把所有空的置为0
}
//返回栈顶元素
public int top(){
if(top <= 0){
System.out.println("栈为空,无法返回栈顶元素");
return -1;
}
return array[top - 1];
}
//返回栈大小
public int size(){
return top;
}
//判空
public boolean isEmpty(){
return top == 0;
}
public void printStack(){
for (int i = 0; i < array.length - 1; i++) {
System.out.print(array[i]);
System.out.print("->");
}
System.out.println();
}
public static void main(String[] args) {
Stack stack = new Stack(20);
for (int i = 0; i < 25; i++) {
stack.push(i);
}
stack.printStack();
stack.pop();
//stack.pop();
stack.printStack();
System.out.println(stack.top());
stack.push(100);
stack.printStack();
System.out.println(stack.isEmpty());
System.out.println("size:" + stack.size());
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容