//通过数组实现栈
public class Stack2 {
private int top = -1;//栈顶指针
private Object[] items;
private int size = 0;
private int capacity = 10;
public Stack2(int capacity){
this.capacity = capacity;
items = new Object[capacity];
}
public Stack2(){
items = new Object[capacity];
}
//移除
public Object pop(){
Object o = null;
if(top > -1){
o = items[top];
top--;
size--;
}
return o;
}
public void push(Object o){
if(capacity == size){
capacity *= 2;
Object[] newItems = new Object[capacity];
for (int i = 0; i < items.length; i++) {
newItems[i] = items[i];
}
items = newItems;
}
items[top+1] = o;
top++;
size++;
}
public int getSize(){
return size;
}
public boolean empty(){
if(top > -1){
return false;
}else{
return true;
}
}
public static void main(String[] args) {
Stack2 stack2 = new Stack2(100);
stack2.push("1");
stack2.push("2");
stack2.push("3");
System.out.println(stack2.pop());
System.out.println(stack2.getSize());
}
}
Java实现栈二:通过数组方式实现
最新推荐文章于 2020-03-06 12:24:18 发布