您的位置:首页 > 职场人生

剑指offer 面试题37 两个链表的第一个公共结点

2014-12-29 13:31 543 查看
struct ListNode{
int data;
ListNode* next;
};
ListNode* FirstShareNode(ListNode* pHead1,ListNode* pHead2){
if(!pHead1||!pHead2) return NULL;
int len1=0,len2=0;
ListNode* pNode1=pHead1;
ListNode* pNode2=pHead2;
//get List1 length
while(pNode1){
pHead1=pHead1->next;
len1++;
}
//get List2 length
while(pNode2){
pHead2=pHead2->next;
len2++
}
//long list go first
if(len1>len2){
for(int i=0;i<len1-len2;++i){
pNode1=pNode1->next;
}
}
else{
for(int i=0;i<len2-len1;++i){
pNode2=pNode2->next;
}
}
//get the 1st share node
while(pNode1!=pNode2 && pNode1 && pNode2){
pNode1=pNode1->next;
pNode2=pNode2->next;
}
//no share node
if(!pNode1) return NULL;
return pNode1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: