Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
这题的思路还是很简单的,首先记录下两个链表的长度,算出长度差(dif)然后设定a,b(b = a+dif)两指针同时开始遍历便可以同时扫到两链表的末尾,由此可以遍历到所有可能是交接点的节点,再判断a==b即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *a = headA, *b = headB;
int lengthA = 0, lengthB = 0;
while (a != NULL)
{
lengthA++;
a = a->next;
}
while (b != NULL)
{
lengthB++;
b = b->next;
}
//a-long b-shrot
if (lengthA >= lengthB)
{
a = headA;
b = headB;
}
else
{
a = headB;
b = headA;
}
for (int i = 0; i < abs(lengthA - lengthB); i++)
{
a = a->next;
}
while (a != b && a && b)
{
a = a->next;
b = b->next;
}
return a;
}
};