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
}
}
};
我的解法的基本思路是,得到两个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
}
}
};
相关文章推荐
- Intersection of Two Linked Lists
- 和大神们学习每天一题(leetcode)-Intersection of Two Linked Lists
- LeetCode -- Intersection of Two Linked Lists
- 【Leetcode】:Intersection of Two Linked Lists
- [LeetCode]Intersection of Two Linked Lists
- [Leetcode 160] Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- LeetCode Intersection of Two Linked Lists
- linked-list-cycle&&find-peak-element&&intersection-of-two-linked-lists
- leetcode[160] Intersection of Two Linked Lists
- lintcode 中等题:Intersection of Two Linked Lists 两个链表的交叉
- 【leetcode】Intersection of Two Linked Lists
- HappyLeetcode42:Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- [LeetCode]160 Intersection of Two Linked Lists
- LeetCode 160 :Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- Intersection of Two Linked Lists
- LeetCode160——Intersection of Two Linked Lists
- LeetCode题解:Intersection of Two Linked Lists