1.相交链表

1.暴力解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <vector>
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
// 先遍历A
ListNode* temp;
// 将地址存在容器中,遍历下一个链表时再一个个比较
std::vector<ListNode*> ln_list;
temp = headA;
while (temp != NULL) {
ln_list.push_back(temp);
temp = temp->next;
}
temp = headB;
while (temp != NULL) {
for (ListNode* node : ln_list)
if (temp == node) {
return temp;
}
temp = temp->next;
}
return NULL;
}
};
这里的时间复杂度是O(nxm),空间复杂度O(n/m)
2.双指针解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <vector>
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* a = headA;
ListNode* b = headB;
while (a != b) {
a = a ? a->next : headB;
b = b ? b->next : headA;
}
return a;
}
};
时间复杂度为O(n+m),空间复杂度O(1)
知识点:
双指针的“对齐”技巧
两条链表长度不同,让两个指针同步走完“自身+对方”的长度,最终同时到达交点或同时到空。
这种“拼接路径”思想可用于:
- 找链表交点
- 找链表环入口
- 合并有序链表找中位数

浙公网安备 33010602011771号