1 package array; 2 /* 3 编写程序,使用一维数组,模拟栈数据结构,包含压栈、弹栈两个方法 4 */ 5 6 public class test01 { 7 public static void main(String[] args) { 8 mystack a=new mystack(); 9 for (int i = 0; i < 15; i++) { 10 a.push("1"); 11 } 12 //a.push("hhh"); 13 for (int i = 0; i < 12; i++) { 14 a.pop(); 15 }//a.pop(); 16 } 17 } 18 19 class mystack{ 20 private Object[] elements; 21 22 public Object[] getElements() { 23 return elements; 24 } 25 public void setElements(Object[] elements) { 26 this.elements = elements; 27 } 28 29 private int a=-1; 30 31 public int getA() { 32 return a; 33 } 34 public void setA(int a) { 35 this.a = a; 36 } 37 38 //无参构造方法,默认栈初始化容量10 39 public mystack() { 40 this.elements=new Object[10]; 41 } 42 43 /*压栈方法*/ 44 public void push(Object obj){ 45 if (a==elements.length-1){ 46 System.out.println("栈已满!压栈失败"); 47 return;} 48 a++; 49 elements[a]=obj; 50 System.out.println("压栈成功!栈帧指向"+a); 51 for (int i = 0; i < a+1; i++) { 52 System.out.print(elements[i]+" "); 53 } 54 System.out.println(); 55 } 56 57 /*弾栈方法*/ 58 public Object pop(){ 59 if (a==-1){ 60 System.out.println("弹栈失败,站内已空"); 61 return 0; 62 } 63 Object x=elements[a]; 64 elements[a]=null; 65 a--; 66 System.out.print("弹栈成功,弹出的内容为"+x+",当前栈内存储情况:"); 67 for (int i = 0; i < a+1; i++) { 68 System.out.print(elements[i]+" "); 69 } 70 System.out.println(""); 71 return x; 72 } 73 }