您的位置:首页 > 其它

leetcode[160]:Intersection of Two Linked Lists

2015-06-07 19:25 393 查看
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:



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.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
int i,l1,l2;
struct ListNode *L,*tmp;
L = headA;
if (headA == NULL || headB == NULL) return NULL;
for( i = 0; L != NULL; i++)
{
L = L->next;
}
l1 = i;
L = headB;
for( i=0; L != NULL;i++)
{
L = L->next;
}
l2 = i;
if (l1 > l2)
{
L = headA;
for( i = 0 ; i < l1 - l2 ; i ++ )
{
L = L->next;
}
tmp = headB;
while(L!= NULL)
{
if(L->val == tmp->val) return L;
L = L->next;
tmp = tmp->next;
}
return NULL;
}
else
{
L = headB;
for( i = 0 ; i < l2 - l1 ; i ++ )
{
L = L->next;
}
tmp = headA;
while(L!= NULL)
{
if(L->val == tmp->val) return L;
L = L->next;
tmp = tmp->next;
}
return NULL;
}

}


两个表后对齐,砍掉较长的表的前段,一个个元素比较就是了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  list