这段代码有什么问题?值不是加入到 t 了吗?

What is wrong with this code? Isn't the values getting joined to t?

我必须合并两个已排序的链表。 我不知道如何,但 t 没有增加。代码有什么错误吗?

Node * p=(Node*)malloc(sizeof(Node)),*t=p;
while(head1!=NULL && head2!=NULL){
    Node * temp=(Node*)malloc(sizeof(Node));

    if(head1->data<=head2->data){
        temp->data=head1->data;
        temp->next=NULL;
        t=temp;

        head1=head1->next;
        t=t->next;
     }
    else{
        temp->data=head2->data;
        temp->next=NULL;
        t=temp;
        t=t->next;
        head2=head2->next;
    }
}
if(head1==NULL){
    t->next=head2;
    printf("%d\n",t->data);
}
else
t->next=head1;


return p;

}

3 1个 2个 3个 成为第一个链表。

3 4个 成为第二个链表

输出必须是: 1 2 3 3 4

我遇到分段错误

如果您想合并 2 个列表,您有多种选择。

  1. 您可以将所有元素复制到一个新列表中。
  2. 您可以从现有列表中删除节点并将其放入新列表中。

你做的就是none这个。

您从选项 1 开始:

while(head1!=NULL && head2!=NULL){
    Node * temp=(Node*)malloc(sizeof(Node));

    if(head1->data<=head2->data){
        temp->data=head1->data;
        temp->next=NULL;
        t=temp;

        head1=head1->next;
        t=t->next;
     }
    else{
        temp->data=head2->data;
        temp->next=NULL;
        t=temp;
        t=t->next;
        head2=head2->next;
    }
}

提示:
您可以通过从 if else 块中提取相同的指令并仅在 else 块之后写入一次来改进您的代码:

while (head1 != NULL && head2 != NULL) {
    Node * temp = malloc(sizeof(Node));
    temp->next = NULL;

    if (head1->data <= head2->data) {
        temp->data = head1->data;   
        head1 = head1->next;
    }
    else {
        temp->data = head2->data;
        head2 = head2->next;
    }

    // Now link the new node:
    t->next = temp;  // <<==== Linking fixed.
    t = t->next;
}

另请注意,您对新节点的 linking 已损坏。您丢失了从 t 到下一个节点的 link。

但是还有一个问题:

到达其中一个列表的末尾后,您将停止复制。 您只需立即将剩余的列表添加到您的新列表中:

if(head1==NULL){
    t->next=head2;
    printf("%d\n",t->data);
}
else
    t->next=head1;

这意味着您没有副本,但每个剩余节点都可以通过 2 个列表重新访问。

对于旧列表,这意味着第一个节点专门 link 通过该列表编辑,但其他节点有 2 个引用。

一旦您开始操作其中一个列表,就可以在一个列表中删除这些节点。然后另一个列表中仍然有一个 link 指向这些节点中的第一个。 当您通过剩余列表访问节点时,这会导致非法内存访问和未定义的行为。这最终会导致分段错误。

您应该复制所有指针。不要在任务中途停止。