首页 > 解决方案 > 使用 C 合并链表

问题描述

我无法理解为什么我的代码无法合并两个排序的链表

C代码:

SinglyLinkedListNode* mergeLists(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
    
SinglyLinkedListNode *temp,*ptr1,*ptr2;

//Merging

      temp=head1;
      while(temp!=NULL)                                 
          temp=temp->next;          

          temp->next=head2;
           temp=head1;
             

                             //Sorting
    int tem;
      
      ptr1=head1;
      
      while(ptr1->next != NULL){                          
          
          ptr2 = ptr1->next;
             while(ptr2 != NULL){
          if((ptr1->data)>(ptr2->data)){
           tem             =   ptr1->data;
           ptr1->data       =   ptr2->data;
           ptr2->data       =   tem;
     }
       ptr2=ptr2->next;
 }
          
          ptr1=ptr1->next;
      }

        return head1;  

}

标签: cmergelinked-listsingly-linked-list

解决方案


  while(temp!=NULL)                                 
      temp=temp->next;          

      temp->next=head2;
       temp=head1;

与以下有很大不同:

while(temp!=NULL) {                               
      temp=temp->next;          
      temp->next=head2;
      temp=head1;
}

大括号很重要,缩进不重要(人类读者除外)。

但是那里仍然存在逻辑错误。您可能打算走到第一个列表的末尾并将第二个列表附加到它,但您走得太远了。也许你想要while(temp->next != NULL)(你需要在进入这样的循环之前添加一个 temp 不为空的检查)。


推荐阅读