|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 HuangRH 于 2020-5-15 06:29 编辑
ResizingArrayStack.java:
import java.util.Iterator;
public class ResizingArrayStack<Item> implements Iterable<Item>{
private Item[] a;
private int N=0;
public ResizingArrayStack(){
a=(Item[])new Object[2];
}
public void push(Item item){
if(N==a.length)resize(2*a.length);
a[N++]=item;
}
public Item pop(Item item){
Item temp= a[--N];
a[N]=null;
if(N>0 && N==a.length/4)resize(a.length/2);
return temp;
}
public boolean isEmpty(){
return N==0;
}
public int size(){
return N;
}
private void resize(int max){
Item[] temp=(Item[])new Object[max];
for(int i=0;i<a.length;i++){
temp[i]=a[i];
}
a=temp;
}
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
public ReverseArrayIterator() {
i = N-1;
}
public boolean hasNext() {
return i >= 0;
}
public void remove() {
}
public Item next() {
return a[i--];
}
}
}
Iterable.java:
import java.util.Iterator;
public interface Iterable<Item> {
Iterator<Item> iterator();
}
然后这里是主程序
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
ResizingArrayStack<String> a=new ResizingArrayStack<String>();
a.push("aaa");
a.push("bbb");
System.out.println(a.size());
Iterator<String> i=a.iterator();
while(i.hasNext()){
String s=i.next();
System.out.println(s);
}
for(String s:a){
System.out.println(s);
}
}
}
while循环可以,for循环不行,我快死了 |
|