在JAVA中将链接列表转换为循环链接列表

时间:2012-12-25 20:07:54

标签: java data-structures

有没有办法将LinkedList类的对象转换为循环链表。

或者java.util中是否有任何预定义的类,如CircularLinkedList 像这样的东西(有些像http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html

任何帮助都会非常感激....

先谢谢:-)

2 个答案:

答案 0 :(得分:3)

不,LinkedList的封装方式使其尾部无法连接。我不认为任何默认集合都支持它,因为它不再符合Iterable的约定,这表示迭代器必须在某个时候到达终点。

当您需要这样的数据结构时,您必须自己实现它。

答案 1 :(得分:0)

看看Guava的Iterables.cycle方法。

public static <T> Iterable<T> cycle(Iterable<T> iterable)

返回一个迭代,迭代器无限循环遍历iterable的元素。

如果iterable.iterator(),迭代器支持remove()。调用remove()后,后续循环将省略已删除的元素,该元素不再可迭代。迭代器的hasNext()方法返回true,直到iterable为空。

请参阅文档:http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#cycle%28java.lang.Iterable%29