package structure_stack;
import java.util.Arrays;
import java.util.EmptyStackException;
/*
* 参考文档:
1.https://www.cnblogs.com/ysocean/p/7911910.html
*/
//模拟java类中的stack,实现自动扩容
public class ArrayStack {
private Object[] elements;
private int top;
private int size;
// 构造一个容量为10的栈
public ArrayStack() {
elements = new Object[10];
this.top = -1;
this.size = 10;
}
// 构造一个容量为intiCapacity的栈
public ArrayStack(int intiCapacity) {
elements = new Object[intiCapacity];
this.top = -1;
this.size = intiCapacity;
}
// 入栈
public Object push(Object object) {
isGrow(top+1);
elements[++top] = object;
return object;
}
// 出栈并返回栈顶元素
public Object pop() {
if(top == -1) {
throw new EmptyStackException();
}
return elements[top--];
}
// 获取栈顶元素
public Object peek() {
if(top == -1) {
throw new EmptyStackException();
}
return elements[top];
}
// 判断是否为空
public boolean isEmpty() {
if(top == -1) {
return true;
}
return false;
}
// 栈中的数组扩容
public boolean isGrow(int minCapcity) {
int oldCapcity = size;
if (minCapcity >= oldCapcity) {
int newCapcity = 0;
if ((minCapcity << 1) - Integer.MAX_VALUE > 0) {
newCapcity = Integer.MAX_VALUE;
} else {
newCapcity = minCapcity << 1;
}
this.size = newCapcity;
elements = Arrays.copyOf(elements, newCapcity);
return true;
}
return false;
}
public void stringReverse(String string) {
ArrayStack arrayStack = new ArrayStack();
char[] cha = string.toCharArray();
for(char c : cha) {
arrayStack.push(c);
}
while(!arrayStack.isEmpty()) {
System.out.print(arrayStack.pop());
}
}
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(2);
arrayStack.push(4);
arrayStack.push(5);
arrayStack.push(6);
arrayStack.stringReverse("how are you");
}
}