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.
找出两条链表的交汇点(如果有)。时间O(n),空间O(1)
这是网站给的做法,很巧妙:
· 让pA、pB两个指针指向A\B两条链表的头结点,二者每次同时向前挪一步
· 当pA移到A表尾时,转到B表的头结点(对,没错!);同样,当pB移到B表尾时,转到A表的头结点
· 如果pA和pB的值相同,那么这个一定是交汇点!
可以用A = {1,3,5,7,9,11} and B = {2,4,9,11}两个链表自己试一下。
· 那么怎样判断A\B无交会点的情况呢?只要记录走的过程中记录A、B表的末尾元素值就行了,如果二者不相等,则一定无交汇点!
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA || !headB)
return NULL;
ListNode *pA = headA, *pB = headB;
int Alast, Blast;
bool hasJunmpedFlagA = false, hasJunmpedFlagB = false;
while (true) {
if (hasJunmpedFlagA && hasJunmpedFlagB && Alast != Blast)
return NULL;
if (hasJunmpedFlagA && hasJunmpedFlagB && pA->val == pB->val)
return new ListNode(pA->val);
if (pA == NULL) {
pA = headB;
hasJunmpedFlagA = true;
}
else {
if (!hasJunmpedFlagA)
Alast = pA->val;
pA = pA->next;
}
if (pB == NULL) {
pB = headA;
hasJunmpedFlagB = true;
}
else {
if (!hasJunmpedFlagB)
Blast = pB->val;
pB = pB->next;
}
}