1,题目要求
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
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.
判断两个链表何时会有交集。
2,题目思路
个人的思路是,先分别找出两个链表的长度,然后利用二者的长度之差,将长的链表“减去”对应的长度,如果两个链表真的有交集的话, 则此时二者在交集处的位置一定是一样的。
另外一种比较有意思的方法,则是利用了两次迭代。第一次迭代,去除两个链表之间的长度差异;第二次迭代,则尝试找到两个链表中节点相等的点。
3,程序源码
方法1:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL || headB == NULL) return NULL;
int lenA = GetListLenHelper(headA), lenB = GetListLenHelper(headB);
int skew = 0;
if(lenA>lenB)
{
skew = lenA - lenB;
while(skew>0){
headA = headA->next;
skew--;
}
}
else{
skew = lenB - lenA;
while(skew>0){
headB = headB->next;
skew--;
}
}
while(headA!=NULL||headB!=NULL)
{
if(headA->val == headB->val)
return headA;
else{
headA = headA->next;
headB = headB->next;
}
}
return NULL;
}
public:
int GetListLenHelper(ListNode *head){
int len = 0;
while(head!= NULL){
head = head->next;
len++;
}
return len;
}
};
方法2:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA == NULL || headB == NULL) return NULL;
ListNode *a = headA;
ListNode *b = headB;
while(a!=b){
a = a == NULL?headB : a->next;//当找到表A的尾部时,a就开始指向表B
b = b == NULL?headA : b->next;//b也一样,这样一定有一个先指向另一个表,也就使得二者的长度之差得到了补偿
//画一个链表图就非常的直观了
//第二轮迭代时,a和b所要遍历的剩余节点的数量都是一样的
//因此即使没有交集,当a遍历到结尾的NULL时,返回值也是正确的
}
return a;
}
};