Intersection of Two Linked Lists
Write a program to find the node at whichthe intersection of two singly linked lists begins.
For example, the following two linkedlists:
begin to intersect at node c1.
Notes:
If the two linked lists have no intersectionat all, return null.
The linked lists must retain their originalstructure after the function returns.
You may assume there are no cycles anywherein the entire linked structure.
Your code should preferably run in O(n)time and use only O(1) memory.
字多有点吓人,题目是这样的,有两条链表,让你找出他们的交汇点。图他给出来,比较形象。有几个notes:1、没有交汇返回NULL;2、链表结构不能改(此类题中,有的思路是把原有链表头尾相连成环做的,这么做也可以,到时都再断开);3、所给链表没有环;4、关联容器阵亡了。
这题编程之美上面有类似问题。
下面我给题目的图示加了几条线。
要是能得到这俩链表如图的位置的指针那该多好啊,然后俩指针同步前移,相遇即是结果,到尾就不相交。那么我们就去找这两个指针。
也就是,让长一点的链表的指针先前移一段距离,这个距离为俩链表的长度差。
所以,先把俩链表走一遍,分别得到长度,进而得到长度差。然后,让指针移到上图的位置去。之后同步前移。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* a = headA;
ListNode* b = headB;
int la = 0;
int lb = 0;
if (headA && headB)
{
while (headA->next && headB->next)
{
headA = headA->next;
headB = headB->next;
}
}
if (headA)
{
la++;
while (headA->next)
{
la++;
headA = headA->next;
}
}
if (headB)
{
lb++;
while (headB->next)
{
lb++;
headB = headB->next;
}
}
if (la > lb)
{
int differ = la - lb;
while (differ > 0)
{
differ--;
a = a->next;
}
}
else
{
int differ = lb - la;
while (differ > 0)
{
differ--;
b = b->next;
}
}
while (a != b)
{
a = a->next;
b = b->next;
}
return a;
}
};