数组模拟栈内存

 1 package mycodes.exception.test2;
 2 /*
 3  * 这个是正常的用数组模拟的栈内存
 4  */
 5 public class Stack {
 6     private String[] arr;
 7     private int p = 0;
 8     public Stack(int len){
 9         arr = new String[len];
10     }
11     
12     //压栈
13     public boolean push(String str) {
14         //不要在这里写循环
15         if(p<arr.length){
16             arr[p++] = str;
17             return true;
18         }else
19             System.out.println("栈已满,无法继续压栈");
20         return false;
21     }
22     
23     //弹栈
24     public String pop() {
25         //不要在这里写循环
26         if(p>0){
27             String str = arr[--p];
28             arr[p] = null;
29             return str;
30         }else
31             System.out.println("栈空,无法弹栈");
32         return null;
33     }
34 }
 1 package mycodes.exception.test2;
 2 /*
 3  * 本类用于测试正常的数组模拟栈内存类Stack
 4  */
 5 public class TestStack {
 6 
 7     /**
 8      * @param args
 9      */
10     public static void main(String[] args) {
11         // TODO Auto-generated method stub
12         Stack s = new Stack(10);
13         for(int i = 1;i<100;i++){
14             if(!s.push("abc"+i))
15                 break;
16         }
17         
18         for(int i = 0;i<100;i++){
19             String str =s.pop();
20             if(str == null)
21                 break;
22             else
23                 System.out.println("弹栈-->" +str );
24         }
25     }
26 
27 }

 

posted @ 2015-11-17 00:33  GoQC  阅读(158)  评论(0)    收藏  举报