使用一维数组模拟栈数据结构,包括压栈,弹栈;
public class MyStack { private Object[] elements; private int index; public MyStack() { this.elements = new Object[10]; //栈的最大长度为10; this.index = -1; //栈帧开始指向-1,表示栈为空; } //压栈方法 public void push(Object obj){ if(this.index >= this.elements.length-1){ System.out.println("压栈失败,栈已满"); return; } index++; elements[index] = obj; System.out.println("压栈"+obj+"成功,栈帧指向"+index); } //弹栈 public void pop(){ if(this.index < 0){ System.out.println("栈为空,弹栈失败"); return; } System.out.println("弹栈"+elements[index]+"成功,栈帧指向"+index); index--; } public Object[] getElements() { return elements; } public void setElements(Object[] elements) { this.elements = elements; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
编写测试程序:
public class MyStackTest { public static void main(String[] args) { MyStack mystack = new MyStack(); //压栈遍历 for (int i = 0; i < 11; i++) { mystack.push(new Object()); } //弹栈遍历 for (int i = 0; i < 11; i++) { mystack.pop(); } } }