为何这段有序链表求交集的C++代码会出现段错误?
有序链表交集求解的段错误问题修复
我尝试实现有序链表的交集求解,运行以下C++代码时出现段错误,题目要求求解两个有序链表的交集。
// Online C++ compiler to run C++ program online #include <bits/stdc++.h> using namespace std; struct Node{ int data; Node *next; Node(int val) { data=val; next=NULL; } }; Node* findIntersection(Node* head1, Node* head2) { // Your Code Here Node* h=nullptr; Node* temp=h; while(head2!=nullptr){ while(head1!=nullptr && head1->data<head2->data){ head1=head1->next; } cout<<head1->data<<endl; if(head1->data==head2->data){ if(h==nullptr){ h=new Node(head1->data); } else{ temp->next=new Node(head1->data); temp=temp->next; } } head2=head2->next; } return h; } int main() { // Write C++ code here Node* l1= new Node(1); l1->next=new Node(2); l1->next->next=new Node(3); l1->next->next->next=new Node(4); l1->next->next->next->next=new Node(6); Node* l2=new Node(2); l1->next=new Node(4); l1->next->next=new Node(6); l1->next->next->next=new Node(8); findIntersection(l1,l2); return 0; }
错误原因分析
- 链表初始化错误:main函数中创建l2后,错误修改了
l1的指针,导致l2始终只有一个节点,原本的l1链表被覆盖,遍历逻辑完全混乱。 - 空指针访问:内层循环结束后未判断
head1是否为空就直接访问head1->data,当head1遍历到末尾变为nullptr时,触发段错误。 - 结果链表指针未同步:初始化结果链表时,
temp指针未跟随h的创建更新,第一次添加节点后temp仍为nullptr,后续temp->next引发空指针错误。 - 未处理提前遍历完成的情况:当
head1遍历完所有节点时,外层循环未终止,持续尝试访问空指针。
修复后的代码
#include <bits/stdc++.h> using namespace std; struct Node{ int data; Node *next; Node(int val) { data=val; next=NULL; } }; Node* findIntersection(Node* head1, Node* head2) { Node* h = nullptr; Node* temp = h; // 同时遍历两个链表,任一为空则终止 while(head1 != nullptr && head2 != nullptr){ if(head1->data == head2->data){ // 创建新节点加入结果链表 if(h == nullptr){ h = new Node(head1->data); temp = h; } else { temp->next = new Node(head1->data); temp = temp->next; } // 同时移动两个指针 head1 = head1->next; head2 = head2->next; } else if(head1->data < head2->data){ // 较小的指针后移 head1 = head1->next; } else { head2 = head2->next; } } return h; } // 辅助函数:打印链表(用于验证结果) void printList(Node* head){ Node* curr = head; while(curr != nullptr){ cout << curr->data << " "; curr = curr->next; } cout << endl; } int main() { // 正确构建第一个链表:1->2->3->4->6 Node* l1 = new Node(1); l1->next = new Node(2); l1->next->next = new Node(3); l1->next->next->next = new Node(4); l1->next->next->next->next = new Node(6); // 正确构建第二个链表:2->4->6->8 Node* l2 = new Node(2); l2->next = new Node(4); l2->next->next = new Node(6); l2->next->next->next = new Node(8); Node* result = findIntersection(l1, l2); printList(result); // 输出:2 4 6 return 0; }
内容的提问来源于stack exchange,提问作者Techy Bhoot
相关产品推荐
相关产品推荐

