Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java combine two linkedlist

I have a question for combining two linkedlist. Basically, I want to append one linkedlist to the other linkedlist.

Here is my solution. Is there a more efficient way to do it without looping the first linkedlist? Any suggestion would be appreciated.

    static Node connect(LinkedList list1, LinkedList list2) {
    Node original = list1.first;
    Node previous = null;
    Node current = list1.first;
    while (current != null) {
        previous = current;
        current = current.next;
    }
    previous.next = list2.first;
    return original;
}
like image 947
caesarkim Avatar asked Dec 02 '25 10:12

caesarkim


2 Answers

Use list1.addAll(list2) to append list2 at the end of list1.

like image 122
Kai Avatar answered Dec 05 '25 01:12

Kai


For linked lists, linkedList.addAll(otherlist) seems to be a very poor choice.

the java api version of linkedList.addAll begins:

public boolean addAll(int index, Collection<? extends E> c) {
    checkPositionIndex(index);
    Object[] a = c.toArray();

so even when you have 2 linked lists, the second one gets converted to an array, then re-constituted into individual elements. This is worse than just merging 2 arrays.

like image 25
Andrew Hill Avatar answered Dec 04 '25 23:12

Andrew Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!