简体   繁体   中英

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!

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:

eg

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...

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?

Easiest possible way....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM