2

Is there any way to convert an object of LinkedList class to a circular linked list.

Or is there any predefined class like CircularLinkedList in java.util Some thing like this (some thing like http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html)

Any help would be really appreciated....

Thanks in Advance :-)

2
  • 6
    What's the end goal. Guava's Iterators.cycle() method might be what you're looking for. You could also wrap the list yourself, it shouldn't be too hard, but it depends what the goal is. Commented Dec 25, 2012 at 20:13
  • 1
    Fun fact: LinkedList is actually internally implemented as a circular linked list, with a dummy header node. Commented Dec 25, 2012 at 23:15

2 Answers 2

3

No, the LinkedList is encapsulated in a way which makes it impossible to connect its tail to its head. I don't think that any of the default collections supports that, because then it wouldn't fulfill the contract for Iterable anymore, which says that an iterator got to get to the end sometime.

When you need a data structure like that, you have to implement it yourself.

Sign up to request clarification or add additional context in comments.

4 Comments

In fact, neither Iterable nor Iterator says anything of the sort. It could very well return true for each call to hasNext().
...and then you pass that to any API which accepts an Iterable, and you caught it in an infinite loop.
I think the key contract that would be broken is the List contract. I don't think an Iterator that returns each element multiple times would be "an iterator over the elements in this list in proper sequence". The last element in the list would appear both before and after the first element.
@Philipp: yes, of course, and that would be a bug like any other bug. If you don't want an infinite loop, then don't pass the infinite iterator to a method that loops endlessly.
1

Have a look at Guava's Iterables.cycle method.

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

Returns an iterable whose iterators cycle indefinitely over the elements of iterable.

That iterator supports remove() if iterable.iterator() does. After remove() is called, subsequent cycles omit the removed element, which is no longer in iterable. The iterator's hasNext() method returns true until iterable is empty.

Refer doc : http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#cycle%28java.lang.Iterable%29 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.