user1657294
user1657294

Reputation: 23

Add linkedlist to linkedlist, JAVA

I want to design a linkedlist to another linkedlist, so far I have this method in MyLinkedList class:

public void addList(int index, E e){
        if(index == 0){
            addFirst(e);
        } else if (index >= size){
            addLast(e);
        }
        else{
            Node<E> current = head;
            for(int i = 1; i < index; i++){
                current = current.next;
            }
            Node<E> temp = current.next;
            current.next = new Node<E>(e);
            (current.next).next = temp;
            size++;
        }
    }

I'm stuck on the method itself, my main program has two LinkedLists that looks like this:

MyLinkedList<String> strings1 = new MyLinkedList<String>();
        strings1.add("java");
        strings1.add("language");
        strings1.add("cooler");
        strings1.add("noob");
        System.out.println(list1);

        MyLinkedList<String> strings2 = new MyLinkedList<String>();
        strings2.add("artistic");
        strings2.add("cereal");
        strings2.add("bowl");
        System.out.println(list2);

Then I wanna add the linkedlist of string2 into linkedlist of string1. How would I do that? I have thought of using

strings1.addList(2, strings2); 

but it didn't work, it won't let me add strings2 to strings1 I'm thinking the output would look like this if I have it done: java, language, artistic, cereal, bowl, cooler, noob or something similar, please help!

Upvotes: 2

Views: 10194

Answers (3)

Captain Obvious
Captain Obvious

Reputation: 785

Use the method addAll(int index, Collection c) to add the two lists together.

strings1.addAll(startIndex, strings2);

You also have to implement the List interface to your class MyLinkedList.. It also isn't really clear what your MyLinkedList class looks like?

Upvotes: 0

Renato
Renato

Reputation: 13690

Easiest possible way....

public void insertList(int index, List<String> list) {
    Collections.reverse(list);
    for (String str : list) {
        add(index, str);
    }
}

Upvotes: 0

Nim
Nim

Reputation: 33655

You have a method in your class which accepts a single node, simply call this as many times as you need for the second list:

e.g.

void addAll(int index, MyList<> second_list)
{
  for(Object o : second_list)
  {
    addList(index, o);
    ++index;
  }
}

The above range based for loop may not work unless your class has implemented the proper interfaces, I'm being lazy - use the normal iteration that your class supports...

Upvotes: 3

Related Questions