简体   繁体   English

合并Java中的两个链表

[英]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.我正在尝试(强调尝试:P)解决一个我需要合并两个排序链表的练习,其中第一个列表的元素首先出现。

My input is:我的输入是:

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

My expected output would be:[1,1,2,3,4,4]我预期的 output 将是:[1,1,2,3,4,4]

The output, which I am actually getting is: [1,1,3,4]我实际得到的 output 是:[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.我合并两个列表的第一个元素,然后仅 append 合并第二个列表,而不是继续合并。 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我可以看到您关于pass by value pass by reference传递的概念不清楚

I would suggest you to google the above phrases我建议你谷歌上面的短语

and for your problem refer to https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/对于您的问题,请参阅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.这与您的问题并不完全相关,但您应该能够解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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