leetcode-master/problems/面试题02.07.链表相交.md

67 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
## 思路
本来很简洁明了的一道题,让题目描述搞的云里雾里的。
简单来说,就是求两个链表交点节点的**指针**。 这里同学们要注意,交点不是数值相等,而是指针相等。
为了方便举例,假设节点元素数值相等,则节点指针相等。
看如下两个链表目前curA指向链表A的头结点curB指向链表B的头结点
<img src='../pics/面试题02.07.链表相交_1.png' width=600> </img></div>
我们求出两个链表的长度并求出两个链表长度的差值然后让curA移动到和curB 末尾对齐的位置,如图:
<img src='../pics/面试题02.07.链表相交_2.png' width=600> </img></div>
此时我们就可以比较curA和curB是否相同如果不相同同时向后移动curA和curB如果遇到curA == curB则找到焦点。
否则循环退出返回空指针。
## C++代码
```
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* curA = headA;
ListNode* curB = headB;
int lenA = 0, lenB = 0;
while (curA != NULL) { // 求链表A的长度
lenA++;
curA = curA->next;
}
while (curB != NULL) { // 求链表B的长度
lenB++;
curB = curB->next;
}
curA = headA;
curB = headB;
// 让curA为最长链表的头lenA为其长度
if (lenB > lenA) {
swap (lenA, lenB);
swap (curA, curB);
}
// 求长度差
int gap = lenA - lenB;
// 让curA和curB在同一起点上末尾位置对齐
while (gap--) {
curA = curA->next;
}
// 遍历curA 和 curB遇到相同则直接返回
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
```
> 更多算法干货文章持续更新可以微信搜索「代码随想录」第一时间围观关注后回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。