链接:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/solution/by-xun-ge-v-4rpz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例![](https://i-blog.csdnimg.cn/blog_migrate/104b85a2fb6b88b2407ec5639f618c42.png)
思路
解题思路
题目意思简单来说,就是求两个链表交点节点的指针。这里同学们要注意,交点不是数值相等,而是指针相等。
双指针法具体实现:
- 为了方便举例,假设节点元素数值相等,则节点指针相等。
- 看如下两个链表,目前curA指向链表A的头结点,curB指向链表B的头结点:
- 我们求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置
- 此时我们就可以比较curA和curB是否相同,如果不相同,同时向后移动curA和curB,如果遇到curA == curB,则找到焦点。
- 否则循环退出返回空指针
此思路其实就是官方题解的思路,那有同学就问了,你的代码这么多,官方的这么短,能一样吗?其实官方题解就是将两个链表接在一起遍历了。而我们是先将链表屁股对其再遍历。
将两个链表接在一起如果两个链表存在相交,那么必然会在最后一段一模一样
代码
简单版双指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* curA = headA;
struct 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) {
int t = lenA;
lenA = lenB;
lenB = t;
struct ListNode * tl = curA;
curA = curB;
curB = tl;
}
// 求长度差
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;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/solution/by-xun-ge-v-4rpz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
简化版双指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if (headA == NULL || headB == NULL) {
return NULL;
}
struct ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA == NULL ? headB : pA->next;
pB = pB == NULL ? headA : pB->next;
}
return pA;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/solution/by-xun-ge-v-4rpz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。