您的位置:首页 > 其它

Lintcode 两个链表的交叉

2015-10-28 23:44 253 查看
请写一个程序,找到两个单链表最开始的交叉节点。

您在真实的面试中是否遇到过这个题? 

Yes

样例

下列两个链表:
A:          a1 → a2
↘
c1 → c2 → c3
↗
B:     b1 → b2 → b3

在节点 c1 开始交叉。

注意

如果两个链表没有交叉,返回
null

在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。

挑战

需满足 O(n) 时间复杂度,且仅用 O(1) 内存。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
// write your code here

int lenA = 0 , lenB = 0;

ListNode *pA = headA, *pB = headB; //这里定义了两个变量pA,pB;编程时候一定要注意,使用的时候一定要知道变量的当前值

while(pA )
{lenA++;pA = pA->next;}
while(pB )
{lenB++;pB = pB->next;}

int d = lenA -lenB;
pA = headA ;pB = headB;
if(lenA < lenB)
{
pA = headB;pB = headA;
d = lenB - lenA;
}

while(d > 0)
{
pA = pA->next;
d--;
}

while(pA != pB)
{
pA = pA->next;
pB = pB->next;
}

return pA;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: