【设计模式】Iterator设计作业-设计LinkedList的iterator

完成了上次迭代器设计的作业: http://blog.csdn.net/acmman/article/details/43920153
LinkedList也需要写一个iterator方法,返回一个实现了Iterator的对象。该如何写?

LinkedList.java:
package cn.edu.hpu.iterator;

public class LinkedList implements Collection{
	Node head=null;//头节点(以后的元素通过next得到)
	Node tail=null;//尾节点
	int size=0;
	public void add(Object o){
		Node n=new Node(o,null);
		if(head==null){
			head=n;
			tail=n;
		}
		tail.setNext(n);
		tail=n;
		size++;
		
	}
	
	public int size(){
		return size;
	}
	
	public Iterator iterator(){
		return new LinkedListIterator();
	}
	
	private class LinkedListIterator implements Iterator{
		private Node node=head;//节点
		
		@Override
		public boolean hasNext() {
			if(node.getNext()==null) return false;
			else return true;
		}


		@Override
		public Object next() {
			Object o=node.getNext().getData();
			node=node.getNext();
			return o;
		}
		
	}
}

Node.java:
package cn.edu.hpu.iterator;


public class Node {
	private Object data;
	private Node next;
	
	
	public Node(Object data, Node next) {
		super();
		this.data = data;
		this.next = next;
	}
	
	public Object getData() {
		return data;
	}
	
	public void setData(Object data) {
		this.data = data;
	}
	
	public Node getNext() {
		return next;
	}
	
	public void setNext(Node next) {
		this.next = next;
	}
	
}

测试
LinkedListTest.java:
package cn.edu.hpu.iterator;


import cn.edu.hpu.iterator.LinkedList;


public class LinkedListTest {
	public static void main(String[] args) {
		Collection c=new LinkedList();
		for(int i=0;i<20;i++){
			c.add(new Cat(i));
		}
		System.out.println(c.size());
		
		LinkedList ll=(LinkedList)c;
		Iterator it=ll.iterator();
		while(it.hasNext()){
			Cat cat=(Cat)it.next();
			System.out.print(cat.getId()+" ");
		}
	}
}

测试结果:
20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 

程序运行正常,作业完成

转载请注明出处:http://blog.csdn.net/acmman/article/details/43924261

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光仔December

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值