简体   繁体   中英

Merge two linked list in Java

I am trying (emphasis on trying:P) solve an exercise where i need to merge two sorted linked list, whereby the element of the first list comes first.

My input is:

[1,2,4] [1,3,4]

My expected output would be:[1,1,2,3,4,4]

The output, which I am actually getting is: [1,1,3,4]

So it looks like, that I m messing something up with the pointers. I merge the first elements of both lists and then just append the second list instead of continuing merging. I m sure its a pretty easy fix, but I am not getting it... :(

Here is my spaghetti code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
       // if one of the lists is null, then return the other one
       if(l1 == null){
           return l2;
       }
       if(l2 == null){
           return l1;
       }
       // create a new list and add the first two elements two it
       ListNode result = l1;
       result.next = l2;
       // introduce a running pointer
       ListNode current = result;
       current = current.next;
       l1 = l1.next;
       l2 = l2.next;
       // Here i assume that the lists have the same length for now
       while(l1 != null && l2 != null){
           current.next = l1;
           current.next.next = l2;
           current = current.next;
           l1 = l1.next;
           l2 = l2.next;  
       }

      return result; 
    }
}

Your algo for the said problem is wrong

I can see your concepts about pass by value and pass by reference are not clear

I would suggest you to google the above phrases

and for your problem refer to https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/

this is not exactly related to your problem but you should be able to figure your way around.

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