Iterator迭代器模式

数据结构分为物理结构和逻辑结构

逻辑结构比如二叉树、List、 stack、 队列 、 b树 、 图

物理结构只有两种:数组和链表

逻辑结构的底层都是由这两种物理结构的一种或两种组合实现。

迭代器模式就是处理集合遍历的。Iterator接口提供hasNext和next方法。各个集合自己内部实现Iterator接口,根据自己的物理结构,实现hasNext和next方法。

public class ListTest {
    public static void main(String[] args) {
        MyList myList = new MyLinkList();
        for(int i=0;i<15;i++){
            myList.add("test"+i);
        }
        System.out.println(myList.size());

        MyIterator iterator = myList.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }
}

​​​​​​​public class MyLinkList implements MyList {
    Node first;
    Node last;
    private int nodeSize = 0;

    @Override
    public void add(Object o) {
        if(nodeSize == 0){
            first = new Node(o);
        }else{
            if(last == null){
                Node newn = new Node(o);
                newn.pre = first;
                newn.next = null;
                first.next = newn;
                last = newn;
            }else{
                Node newn = new Node(o);
                last.next = newn;
                newn.next = null;
                newn.pre = last;
                last = newn;
            }
        }
        nodeSize++;
    }

    @Override
    public int size() {
        return nodeSize;
    }

    @Override
    public Object get(int index) {
        if(index < (nodeSize>>1)){
            Node n = first;
            for(int i = 0;i<index;i++){
                n = n.next;
            }
            System.out.println("正向遍历");
            return n.o;
        }else{
            Node n = last;
            for(int i=nodeSize-1; i>index;i--){
                n = n.pre;
            }
            System.out.println("倒序遍历");
            return n.o;
        }
    }

    @Override
    public MyIterator iterator() {
        return new LinkListIterator(nodeSize);
    }

    class Node{
        Object o;
        Node pre;
        Node next;
        public Node(Object o){
            this.o = o;
        }
    }

    private class LinkListIterator implements MyIterator{

        private int curr;
        private int startInd = 0;

        public LinkListIterator(int nodeSize) {
            this.curr = nodeSize;
        }

        @Override
        public boolean hasNext() {
            return startInd < curr;
        }

        @Override
        public Object next() {
            return get(startInd++);
        }
    }

}


public interface MyIterator {
    boolean hasNext();
    Object next();
}

public interface MyList {
    void add(Object o);
    int size();
    Object get(int i);
    MyIterator iterator();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值