栈的实现Java

 1 package practice;
 2 
 3 import java.util.Iterator;
 4 //
 5 public class MyStack<T> implements Iterable<T> {
 6     private T[] a;
 7     private int p = 0;
 8     @SuppressWarnings("unchecked")
 9     public MyStack() {
10         a = (T[]) new Object[1];
11     }
12     
13     public void push(T elements) {
14         if (a.length == p) {resize(2*a.length);}
15         a[p++] = elements;
16     }
17     
18     public T pop() {
19         if (a.length/4 == p) {resize(a.length/2);}
20         return a[--p];
21     }
22     
23     @SuppressWarnings("unchecked")
24     public void resize(int length) {
25         T[] b = (T[]) new Object[length]; //将数组长度改变
26         for (int i = 0; i < p; i++) { //将数组复制
27             b[i] = a[i];
28         }
29         a = b; //让a指向b的内存空间
30     }
31     
32     public boolean isEmpty() {
33         return p == 0;
34     }
35     
36     public int size() {
37         return p;
38     }
39     @Override
40     public Iterator<T> iterator() { //使数据结构可以让foreach访问
41         return new ArrayIterator();
42     }
43     private class ArrayIterator implements Iterator<T>{
44         
45         private int p2 = 0;
46         
47         @Override
48         public boolean hasNext() { //return false 则foreach终止
49             return p2 != p;
50         }
51 
52         @Override
53         public T next() { //foreach 寻找下一个元素
54             return a[p2++];
55         }
56     }
57 }

 

posted @ 2017-07-27 13:38  zhangqi66  阅读(192)  评论(0编辑  收藏  举报