【问题标题】:Merge 2 sorted linked list wrong answer合并2个排序链表错误答案
【发布时间】:2020-04-03 00:56:08
【问题描述】:

所以我正在做关于合并两个排序链表的hackerrank问题。这就是我所拥有的

    // Complete the mergeLists function below.

    /*
     * For your reference:
     *
     * SinglyLinkedListNode {
     *     int data;
     *     SinglyLinkedListNode next;
     * }
     *
     */
    static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {

        SinglyLinkedListNode curr1 = head1;
        SinglyLinkedListNode curr2 = head2;
        SinglyLinkedListNode head = new SinglyLinkedListNode(0);
        SinglyLinkedListNode curr = head;



        while(curr1.next != null && curr2.next != null){

            if(curr1.data < curr2.data ){

               curr.next = curr1;
               curr = curr.next;
               curr1 = curr1.next;


            }

            else{

                curr.next = curr2;
                curr=curr.next;
                curr2 = curr2.next;
            }

        }

        if (curr1.next == null ){
            curr.next = curr2;
        }


        head = head.next;
        return head;


    }

    private static final Scanner scanner = new Scanner(System.in);

然而这是我得到的输出

1 2 3 4 与

相反

1 2 3 3 4

测试用例是

链表 1 : 1,2,3 链表2:3,4

【问题讨论】:

  • 由于curr2.next == nullcurr1.next 不是null 而循环结束时会发生什么?
  • @jeppe 是同样的错误
  • @lurker 我在这里不小心删除了它,但是当 curr1.next 为空时它也是一样的。我把它放回去了,还是一样的错误
  • 是因为while循环中的条件。您没有考虑第一个链表中的最后一个元素,因为它的下一个元素为空。你的逻辑看起来不对

标签: java merge linked-list


【解决方案1】:

当两个元素彼此相等时,您缺少if 子句。

        else if (curr1.data > curr2.data) {
            curr.next = curr2;
            curr = curr.next;
            curr2 = curr2.next;
        } else {
            // assign node from 2nd list
            curr.next = curr2;

            // increment 2nd list
            curr2 = curr2.next;
            curr = curr.next;

            // asign node from 1st list
            curr.next = curr1;

            // increment 1st list
            curr1 = curr1.next;
            curr = curr.next;
        } 

【讨论】:

  • 仍然与我上面的答案相同,为 1,2,3,4 而不是 1,2,3,3,4
  • 能不能把System.out.println放到debug
【解决方案2】:

当其中一个完成时,您需要将头部分配给剩余列表。这发生在两个列表大小不同的情况下:

替换

if (curr1.next == null ){
    curr.next = curr2;
}

if (curr1.next == null ){
    curr.next = curr2;
} else if (curr2.next == null ){
    curr.next = curr1;
}

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2019-06-19
    • 1970-01-01
    相关资源
    最近更新 更多