2、利用c++,给定两个单链表,编写算法找出两个链表的公共结点。
时间: 2024-10-07 11:01:02 浏览: 59
在C++中,找到两个单链表的公共节点可以使用双指针法。这个方法的基本思想是,分别从两个链表的头部开始,同时前进,如果它们指向相同的节点,则说明找到了公共节点。当其中一个链表遍历完时,另一个链表应该还在继续遍历,直到遇到相同的节点或者到达链表尾部。
下面是一个简单的C++函数,它接收两个链表的头节点作为输入,并返回第一个公共节点,如果没有公共节点则返回nullptr:
```cpp
#include <iostream>
using namespace std;
// 链表节点结构
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* findIntersectionNode(ListNode* list1, ListNode* list2) {
if (!list1 || !list2) return nullptr; // 如果任何一个链表为空,直接返回null
// 让快指针先走一步
ListNode* fast = list1;
ListNode* slow = list1;
// 当快慢指针都指向链表尾部时,它们相交
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) break;
}
// 如果没相交,直接返回
if (!fast || !fast->next) return nullptr;
// 从链表头部开始,让两个指针再次相遇
fast = list1;
slow = slow->next;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast; // 返回公共节点
}
int main() {
// 测试示例
ListNode* list1 = new ListNode(1);
list1->next = new ListNode(2);
list1->next->next = new ListNode(3);
list1->next->next->next = new ListNode(4);
list1->next->next->next->next = new ListNode(5);
ListNode* list2 = new ListNode(6);
list2->next = new ListNode(7);
list2->next->next = new ListNode(8);
list2->next->next->next = list1->next->next; // 列表2的部分链路与列表1共享
ListNode* intersection = findIntersectionNode(list1, list2);
if (intersection)
cout << "Intersection node found: " << intersection->val << endl;
else
cout << "No intersection found." << endl;
return 0;
}
```
在这个示例中,我们创建了两个链表,其中`list2`的一部分与`list1`有共同节点。`findIntersectionNode`函数会找到这两个链表的第一个公共节点。如果没有公共节点,函数将返回nullptr。
阅读全文
相关推荐


















