栈的实现Java

 package practice;

 import java.util.Iterator;
//栈
public class MyStack<T> implements Iterable<T> {
private T[] a;
private int p = 0;
@SuppressWarnings("unchecked")
public MyStack() {
a = (T[]) new Object[1];
} public void push(T elements) {
if (a.length == p) {resize(2*a.length);}
a[p++] = elements;
} public T pop() {
if (a.length/4 == p) {resize(a.length/2);}
return a[--p];
} @SuppressWarnings("unchecked")
public void resize(int length) {
T[] b = (T[]) new Object[length]; //将数组长度改变
for (int i = 0; i < p; i++) { //将数组复制
b[i] = a[i];
}
a = b; //让a指向b的内存空间
} public boolean isEmpty() {
return p == 0;
} public int size() {
return p;
}
@Override
public Iterator<T> iterator() { //使数据结构可以让foreach访问
return new ArrayIterator();
}
private class ArrayIterator implements Iterator<T>{ private int p2 = 0; @Override
public boolean hasNext() { //return false 则foreach终止
return p2 != p;
} @Override
public T next() { //foreach 寻找下一个元素
return a[p2++];
}
}
}
上一篇:ios图片剪切


下一篇:基于PLC1850平台的ARP包请求与响应