GFG题实现合并排序链表

GFG question implementation merge sorted linked list

https://practice.geeksforgeeks.org/problems/merge-two-sorted-linked-lists 我试着写了这个问题的代码,写了两个可能的答案。一个工作,一个没有。我需要知道原因。为什么? 实施 1 -

class LinkedList
{
    //Function to merge two sorted linked list.
    Node sortedMerge(Node head1, Node head2) {
        Node beforeHead = new Node(-1);
        Node temp = beforeHead;
        temp = temp.next;
        while(head1!=null && head2!=null){
            if(head1.data<head2.data){
                temp = head1;
                head1 = head1.next;
            }else{
                temp = head2;
                head2 = head2.next;
            }
            //System.out.println(temp.data);
            //System.out.println(temp.next);
            temp = temp.next;
        }
        
        while(head1!=null){
            temp = head1;
            head1 = head1.next;
            temp = temp.next;
        }
        
        while(head2!=null){
            temp = head2;
            head2 = head2.next;
            temp = temp.next;
        }
       
        //System.out.println(beforeHead.next);
        return beforeHead.next;
   } 
}

引用有问题,但我找不到原因。

实施 2 -

class LinkedList
{
    //Function to merge two sorted linked list.
    Node sortedMerge(Node head1, Node head2) {
        Node beforeHead = new Node(-1);
        Node temp = beforeHead;
        while(head1!=null && head2!=null){
            if(head1.data<head2.data){
                temp.next = head1;
                head1 = head1.next;
            }else{
                temp.next = head2;
                head2 = head2.next;
            }
            
            temp = temp.next;
        }
        
        while(head1!=null){
            temp.next = head1;
            head1 = head1.next;
            temp = temp.next;
        }
        
        while(head2!=null){
            temp.next = head2;
            head2 = head2.next;
            temp = temp.next;
        }
       
        //System.out.println(beforeHead.next);
        return beforeHead.next;
   } 
}

提前致谢。

在第一次实施中,最初temp= beforeHead->next。这是 Null.

我了解到您正在使用所需的值初始化 temp 变量。 但是这些临时值究竟在哪里链接。对于每次迭代,temp 值都会更改,但不会与之前的值相关联。

所以最终创建了所有节点,但其中 none 个是链接的。