c - 使用 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;
}
解决方案
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 不为空的检查)。
推荐阅读
- java - 我应该关心 File#separator for Path#resolve(String)
- python - 在二进制字符串中查找子字符串
- delphi - Delphi Win32 TXMLDocument 不能从线程中实例化和使用?
- flutter - iOS Simulator 部署目标设置为 8.0,但支持的部署目标版本范围为 9.0 到 15.0.99
- javascript - 如何导入从 html 导入 .json 的 .js
- c# - API 请求中不支持的接口类型的反序列化
- docker - 将depend_on与堆栈一起使用
- reactjs - p5.js 和 React:当组件的一个道具更新时如何更新组件内的草图
- python - 如何为python中列表的每个元素添加一个固定键?
- jenkins - 如何在詹金斯中运行机器人测试命令