简体   繁体   中英

Merge Two Linked Lists using Java

Trying to figure out what I'm missing in my code that is supposed to merge linked list 2 to the end of linked list 1. Right now it's just getting the last element in the second list and returning that.

The logic I was trying to use is walking down the first list (L1) and adding those elements one-by-one to new_list then doing the same for the second list (L2) after I've reached the end of L1. I am also trying to avoid modifying L1 or L2, which is why I created a new_list.

Any help would be greatly appreciated.

public NodeList(int item, NodeList next) {
    this.item = item;
    this.next = next;
}

public static NodeList merge(NodeList l1, NodeList l2) {

    NodeList new_list = new NodeList(l1.item, l1.next);
    NodeList new_list2 = new NodeList(l2.item, l2.next);

    while (true) {
        if (new_list.next == null) {
            if (new_list2.next == null) {
                return new_list;
            }
            else {
                new_list.next = new NodeList(new_list2.next.item, new_list2.next.next);
                new_list2 = new_list2.next;
            }

        }
        else {
            new_list.next = new NodeList(new_list.next.item, new_list.next.next);
            new_list = new_list.next;
        }
    }
}

You need to retain a reference to the first node in your list, which you do not do. In the example below, I also break up your loop into two loops with predetermined termination conditions, since that is logically what you are trying to do. Note that I never copy a reference to the existing list's elements, since you mentioned that you never want to modify them. I do however increment the local reference to the inputs:

public static NodeList merge(NodeList l1, NodeList l2) {

    NodeList new_head = new NodeList(0, null);
    NodeList new_node = new_head;

    for(; l1 != null; l1 = l1.next) {
        new_node.next = new NodeList(l1.item, null);
        new_node = new_node.next;
    }

    for(; l2 != null; l2 = l2.next) {
        new_node.next = new NodeList(l2.item, null);
        new_node = new_node.next;
    }
    return new_head.next;
}

As you can see, this has a lot of code repetition, so it can easily be generalized for an arbitrary number of lists:

public static NodeList merge(NodeList... l) {

    NodeList new_head = new NodeList(0, null);
    NodeList new_node = new_head;

    for(NodeList ln in l) {
        for(; ln != null; ln = ln.next) {
            new_node.next = new NodeList(ln.item, null);
            new_node = new_node.next;
        }
    }
    return new_head.next;
}

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