shz.core.stack.a.ZArrayStack Maven / Gradle / Ivy
package shz.core.stack.a;
import java.util.Arrays;
/**
* 元素类型为boolean基于动态数组的栈
*
* 24+n(n为元素个数)=es
*
* B=48+n+对齐填充
*/
public class ZArrayStack extends ArrayStack {
protected boolean[] es;
protected ZArrayStack(int capacity) {
super(capacity);
es = new boolean[capacity];
}
public static ZArrayStack of(int capacity) {
return new ZArrayStack(capacity);
}
public static ZArrayStack of() {
return of(DEFAULT_CAPACITY);
}
@Override
protected final Boolean get(int i) {
return es[i];
}
@Override
protected final void resize(int capacity) {
this.capacity = capacity;
es = Arrays.copyOf(es, capacity);
}
@Override
protected final void setNull(int i) {
es[i] = false;
}
public final void push(boolean e) {
beforePush();
es[size++] = e;
}
public final boolean pop() {
boolean e = es[--size];
afterPop();
return e;
}
public final boolean peek() {
return es[size - 1];
}
public final void reverse() {
if (size == 0) return;
//栈底移至栈顶
bottomToTop();
boolean top = es[size - 1];
pop();
reverse();
push(top);
}
private void bottomToTop() {
if (size == 0) return;
boolean top1 = es[size - 1];
pop();
if (size == 0) push(top1);
else {
bottomToTop();
boolean top2 = es[size - 1];
pop();
//交换栈顶 与 子栈顶
push(top1);
push(top2);
}
}
}