繁体   English   中英

合并Java中的两个链表

[英]Merge two linked list in Java

我正在尝试(强调尝试:P)解决一个我需要合并两个排序链表的练习,其中第一个列表的元素首先出现。

我的输入是:

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

我预期的 output 将是:[1,1,2,3,4,4]

我实际得到的 output 是:[1,1,3,4]

所以看起来,我把指针弄乱了。 我合并两个列表的第一个元素,然后仅 append 合并第二个列表,而不是继续合并。 我相信这是一个很容易解决的问题,但我没有得到它...... :(

这是我的意大利面条代码:

/**
 * 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; 
    }
}

您对上述问题的算法是错误的

我可以看到您关于pass by value pass by reference传递的概念不清楚

我建议你谷歌上面的短语

对于您的问题,请参阅https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/

这与您的问题并不完全相关,但您应该能够解决问题。

暂无
暂无

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

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