leetcode 160. Intersection of Two Linked Lists
(Easy)
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
Example 1:
Example 2:
Example 3:
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.
-
核心问题: 找到两个有交点的链表的交点
-
思路一: 使用hash_map,遍历A中节点,将其加入,然后检查B中每一个节点. (不写了)
-
思路二: 使用两个指针(Two Pointer),pA,pB,初始指向A,B的head
每次都将指针向后推进一个元素,如果pA到达尾部,则让其指向pB head,如果pB到达尾部,则让其指向pA head
这样两个指针相遇时则是所求的节点.
妙啊,简单而又巧妙的想法
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *pa = headA;
ListNode *pb = headB;
int check = 2;
while(pa != NULL && pb != NULL)
{
if(pa == pb)
return pa;
pa = pa->next;
if(pa == NULL && check)
{
pa = headB;
check--;
}
pb = pb->next;
if(pb == NULL && check)
{
pb = headA;
check--;
}
}
return NULL;
}
};