数据结构——栈和队列

已知的数据结构:数组、链表、哈希表(数组+链表)、二叉树[详情见集合[容器]篇]

<-------栈-------->

  

模拟栈
  使用数组,模拟一个栈结构和对栈的操作
    如果栈已经满了,提示压栈失败,栈已经满了
    出栈操作,如果栈已经空了,提示 出栈失败,栈已经空了

 1 public class MyStack<T> {
 2     //栈的最大容量
 3     private final int CAPACITY;
 4     //用来存放对象的模拟栈的数组
 5     private T[] values;
 6     //指向栈顶的指针
 7     private int index;
 8     @SuppressWarnings("unchecked")
 9     public MyStack(int capacity) {
10         this.CAPACITY = capacity;
11         this.values = (T[])new Object[capacity];
12         index = 0;
13     }
14     /**
15      * 压栈操作
16      * @param item
17      * @return 压栈的对象
18      */
19     public void push(T item){
20         if(index >= CAPACITY){
21             System.out.println("提示压栈失败,栈已经满了。");
22             return;
23         }
24         values[index] = item;
25         index ++;
26     }
27     /**
28      * 出栈操作
29      * @return 出栈的对象
30      */
31     public T pop(){
32         if(index <= 0){
33             System.out.println("提示 出栈失败,栈已经空了。");
34             return null;
35         }
36         index --;
37         return values[index];
38     }
39     /**
40      * 得到栈的容量
41      * @return 
42      */
43     public int capacity(){
44         return this.CAPACITY;
45     }
46     /**
47      * 得到栈中元素的数量
48      * @return
49      */
50     public int size(){
51         return this.index;
52     }
53     
54     /**
55      * 清栈操作
56      */
57     public void clear(){
58         this.index = 0;
59     }
60     /**
61      * 栈是否为空
62      * @return
63      */
64     public boolean isEmpty(){
65         return index == 0;
66     }
67     
68     /**
69      * 打印栈中的内容
70      */
71     public String toString(){
72         return Arrays.toString(Arrays.copyOf(values, this.index));
73     }
74 }

测试栈模拟器

 1 //测试自定义栈
 2 import java.util.*;
 3 
 4 class Test {
 5 
 6     public static void main(String[] args) {
 7         MyStack<String> myStack = new MyStack<String>(6);
 8 
 9         myStack.pop(); // 提示压栈失败,栈已经满了。
10         myStack.push("1");
11         myStack.push("2");
12         myStack.push("3");
13 
14         myStack.push("4");
15         myStack.push("5");
16         myStack.push("6");
17 
18         myStack.push("7"); // 提示压栈失败,栈已经满了。
19         System.out.println(myStack); // [1, 2, 3, 4, 5, 6]
20 
21         System.out.println(myStack.pop()); // 6
22 
23         System.out.println(myStack); // [1, 2, 3, 4, 5]
24         System.out.println(myStack.isEmpty()); // false
25 
26         System.out.println("栈的容量:" + myStack.capacity()); // 栈的容量:6
27         System.out.println("栈内元素的数量:" + myStack.size()); // 栈内元素的数量:5
28         myStack.clear(); // 栈内元素的数量:5
29         System.out.println("栈的容量:" + myStack.capacity()); // 栈的容量:6
30         System.out.println("栈内元素的数量:" + myStack.size()); // 栈内元素的数量:0
31 
32         System.out.println(myStack); // []
33 
34         System.out.println(myStack.isEmpty()); // true
35 
36     }
37 }

<-------队列-------> 

 

posted @ 2016-08-25 19:53  IT蓄水池  阅读(101)  评论(0)    收藏  举报