ITeye博客

java实现Iterable接口的栈(stack)

akingde · 2014-03-23 16:32 · 设计模式 · 编程语言 · Markdown

//实现Iterable接口,实现迭代遍历
   public class Stack<Item> implements Iterable<Item>{
private Node first;
private int N;
//定义内部类作为栈中的每一个节点
private class Node{
    Item item;
    Node next;
}
public boolean isEmpty(){
    return first==null;
}
public  int size(){
    return N;
}
public void push(Item item){
    Node oldFirst = first;
    first=new Node();
    first.item= item;
    first.next=oldFirst;
    N++;
}

public Item pop(){
    Item item=first.item;
    first = first.next;
    N--;
    return item;
}
//实现迭代遍历时返回的Iterator
private class AIterator implements Iterator<Item>{
    private Node current=first;
    public boolean hasNext(){return current!=null;}
    public Item next(){
        Item item=current.item;
        current=current.next;
        return item;
    }
    @Override
    public void remove() {
    }
}
@Override
public Iterator<Item> iterator() {
    return new AIterator();
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。