您的位置:首页 > 其它

【leetcode】Intersection of Two Linked Lists

2015-05-07 18:42 218 查看

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.

思路:

链表的题目第一次一次通过。。。基本思路就两个链表的长度差就是两个链表在相交之前数据的个数差,找到这个差之后,再一对一逐个对比,就可以了。

/**
* 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==NULL||headB==NULL) return NULL;
ListNode *res, *p1, *p2;
p1=headA;
p2=headB;
int a=0,b=0;
while(p1&&p2)
{
p1=p1->next;
p2=p2->next;
a++;b++;
}
while(p1){p1=p1->next;a++;}
while(p2){p2=p2->next;b++;}

int delta=abs(a-b);
p1=headA;
p2=headB;
if(a>=b)
{
for(int i=0;i<delta;i++)
{
p1=p1->next;
}
}
else
{
for(int i=0;i<delta;i++)
{
p2=p2->next;
}
}

while(p1&&p2)
{
if(p1->val==p2->val)
return p1;
else
{
p1=p1->next;
p2=p2->next;
}
}
return NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: