public class MyStack {
private Object[] data;
private int index;
public MyStack() {
data = new Object[10];
index=-1;
}
public MyStack(Object[] data, int index) {
this.data = data;
this.index = index;
}
public Object[] getData() {
return data;
}
public void setData(Object[] data) {
this.data = data;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public void push(Object obj){
if(index==this.data.length-1){
System.out.println("栈已满,压栈失败");
return;
}
this.data[++index]=obj;
System.out.println("数据"+obj+"已经被压入到栈中,在栈中的位置为"+index);
}
public Object pop(){
if(index==-1){
System.out.println("栈已空,出栈失败");
return null;
}
System.out.println("数据"+this.data[index]+"已经被弹出栈中"+index);
return this.data[index--];
}
}
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.push(new Object());
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
myStack.pop();
}
}
|