编程导航算法村第四关 | 青铜挑战
基于数组创建栈
- 思路:
- 创建一个初始数组array,初始大小为0,;
- 当添加元素是,如果array已满,则将扩容array数组的50%
public class ArrayStack {
private int[] arrys;
private int top = 0;
public ArrayStack() {
this.arrys = new int[10];
}
public void push(int element) {
if (top >= this.arrys.length) {
this.copyContaner(top);
}
this.arrys[top++] = element;
}
public int pop() {
if (top == 0) {
return 0;
}
int arry = this.arrys[top - 1];
top--;
return arry;
}
public boolean isEmpty() {
return top == 0;
}
public int peek() {
return this.arrys[top - 1];
}
private void copyContaner(int size) {
int length = this.arrys.length;
if (size >= length) {
size = size + (size / 2 + 1);
this.arrys = Arrays.copyOf(this.arrys, size);
System.out.println(size + "," + this.arrys.length);
}
}
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(5);
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
arrayStack.push(4);
arrayStack.push(4);
arrayStack.push(4);
arrayStack.push(4);
System.out.println(arrayStack.pop());
System.out.println(arrayStack.pop());
System.out.println(arrayStack.pop());
System.out.println(arrayStack.pop());
if (!arrayStack.isEmpty()) {
System.out.println(arrayStack.pop());
}
}
}