-1

I want to duplicate the elements in a linked list. This is what I have tried:

public class duplicate  {
      public static void main(String[] args) {

        LinkedList <Integer> list = new LinkedList<Integer>() ;
        list.add(2); 
        list.add(3); 
        list.add(4); 
        list.add(1); 
        list.add(0); 

        for( int i= 0 ; i<list.size(); i++) {   
          list.addAll(list);
          System.out.println(list);
          break; 
        }

      }
    }

But I got an infinite loop.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • 1
    Because you are adding elements to the list in a loop so `list.size()` grows every iteration. – Michał Krzywański May 08 '19 at 10:02
  • Well, you keep increasing the length of the list at each iteration, and your loop only stops when i is equal to the size of the list. – JB Nizet May 08 '19 at 10:03
  • 3
    After each iteration of the for loop the `list.size()` returns a bigger number. Why do you even need that loop? A single call of `list.addAll(list);` should be enough to duplicate the list. – Amongalen May 08 '19 at 10:03
  • she has used `break` the loop should stop after first itertion – Danyal Sandeelo May 08 '19 at 10:07
  • Either use the `addAll` or the `loop`, but not both at the same time – EpicPandaForce May 08 '19 at 10:09
  • I can't reproduce it. Is that exactly your code? – talex May 08 '19 at 10:13
  • this would stop in first iteration, this is working fine here – Danyal Sandeelo May 08 '19 at 10:14
  • 1
    By the way, ArrayList should almost always be preferred over LinkedList. See https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist-in-java and especially https://twitter.com/joshbloch/status/583813919019573248 where even the author of Java's LinkedList doesn't use it. – Klitos Kyriacou May 08 '19 at 10:21

3 Answers3

2

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation) (...)

So, just by doing this you're fine:

LinkedList <Integer> list = new LinkedList<Integer>() ;
//... code omitted (adds every number)
list.addAll(list);
  • However, if you want to use List.add instead of List.addAll you can do it like this (need to use for-loop):

    LinkedList <Integer> list = new LinkedList<Integer>() ;
    //... code omitted (adds every number)
    int initialSize = list.size();
    for( int i = 0 ; i < initialSize; i++) {   
      list.add(list.get(i));
    }
    
    System.out.println(list);
    
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
0

you are adding the list elements again and again in the for loop.

for(int i= 0 ; i < list.size(); i++) {   
   list.addAll(list);
   System.out.println(list);
}

Every time it will grow & which leads the size to grow for each iteration. correct the step. Either use a local variable to store the size or change your logic

Swapnil Patil
  • 613
  • 6
  • 23
Shriram
  • 4,343
  • 8
  • 37
  • 64
0

You can simply do list.addAll(list);.

If you want to use the add method as an exercise, you need to be careful to save the original size of the list before you start iterating. You can do it in the initialization part of your for loop:

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>(Arrays.asList(2, 3, 4, 1, 0));
    for (int i = 0, size = list.size(); i < size; i++)
        list.add(list.get(i));
    System.out.println(list);
    assert list.equals(Arrays.asList(2, 3, 4, 1, 0, 2, 3, 4, 1, 0));
}

Now you'll notice the above uses ArrayList, rather than LinkedList. In general, you should prefer ArrayList. Even the author of Java's LinkedList says he doesn't use it. See also this SO question about ArrayList vs LinkedList.

If you have to use LinkedList, you can just replace the second line from the above to this:

    List<Integer> list = new LinkedList<>(Arrays.asList(2, 3, 4, 1, 0));

The rest of the code can remain unchanged. However, if you have a very long list, then using the get(index) method of the LinkedList class can reduce performance. With LinkedList, you get higher performance if you iterate (using LinkedList.iterator() or an enhanced for loop, than by using a plain for loop with get() calls. But you can't iterate over the list while adding to it, as you'll then get a ConcurrentModificationException. Instead, you can copy the linked list to an array and iterate over that, while adding to the list:

public static void main(String[] args) {
    List<Integer> list = new LinkedList<>(Arrays.asList(2, 3, 4, 1, 0));
    for (Integer element : list.toArray(new Integer[0])) {
        list.add(element);
    }
    System.out.println(list);
    assert list.equals(Arrays.asList(2, 3, 4, 1, 0, 2, 3, 4, 1, 0));
}
Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
  • this is for an array, I need to duplicate list in a single linked list – Duaa Aljamal May 08 '19 at 10:35
  • @DuaaAljamal an ArrayList is not an array. It's a list (which happens to use an array internally in its implementation). If you really need to use a LinkedList (why?) then simply replace ArrayList with LinkedList in the second line above, and everything else is the same. But I'll edit my answer for clarification in a minute. – Klitos Kyriacou May 08 '19 at 11:59