您的位置:首页 > 编程语言 > Go语言

Intersection of Two Linked Lists

2015-02-09 09:49 169 查看
时间复杂度为O(n^2)或者空间复杂度为O(n)的解法很容易想到,但都不满足题目要求。

我的解法的基本思路是,得到两个list的长度,顺便比较它们的结尾,如果结尾不相同,则两个list肯定不相交。否则将两个list的长度对齐,然后同时向前齐步走,如果它们相遇了,那么相遇的节点即为相交节点。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(!headA)
{
return NULL;
}
if(!headB)
{
return NULL;
}
ListNode* tmpA=headA;
ListNode* tmpB=headB;
int lenA=0;
int lenB=0;
while(tmpA->next)
{
lenA++;
tmpA=tmpA->next;
}
lenA++;
while(tmpB->next)
{
lenB++;
tmpB=tmpB->next;
}
lenB++;
if(tmpA!=tmpB)
{
return NULL;
}
else
{
tmpA=headA;
tmpB=headB;
if(lenA>lenB)
{
while(lenA>lenB)
{
tmpA=tmpA->next;
lenA--;
}
}
else
{
while(lenB>lenA)
{
tmpB=tmpB->next;
lenB--;
}
}
while(lenA)
{
if(tmpA==tmpB)
{
return tmpA;
}
tmpA=tmpA->next;
tmpB=tmpB->next;
lenA--;
}
return NULL;//impossible
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode