【问题标题】:Merging Linked Lists using C使用 C 合并链表
【发布时间】:2020-07-25 18:12:36
【问题描述】:

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

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;  

}

【问题讨论】:

  • 不起作用 只是没有任何意义。请准确说出会发生什么,最小的main 包含初始化列表以及预期和实际输入。换一种说法,请提供一个真实的minimal reproducible example,我们可以复制。
  • while(temp!=NULL) temp=temp->next; 离开 temp == NULL。下一行是temp->next = head2,它试图取消对NULL 的引用。也许您的剪切和粘贴未能包含大括号。 “不工作”是否意味着“运行时段错误”?

标签: c merge linked-list singly-linked-list


【解决方案1】:
  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 不为空)。

【讨论】:

  • :) 我只是忘记检查循环,现在它通过了所有测试用例。 while(temp->next!=NULL) { temp=temp->next; } temp->next=head2; temp=head1;
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 2010-12-25
  • 1970-01-01
  • 2015-08-11
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多