您的位置:首页 > 其它

两个链表的第一个公共结点

2015-12-10 21:52 197 查看
输入两个链表,找出它们的第一个公共结点。

/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
int length1=GetLength(pHead1);
int length2=GetLength(pHead2);

if(length1<length2){
ListNode* temp=pHead2;
pHead2=pHead1;
pHead1=temp;
int tempInt=length2;
length2=length1;
length1=tempInt;
}

for(int i=0;i<length1-length2;i++)
pHead1=pHead1->next;
for(int i=0;i<length2;i++)
if(pHead1==pHead2)
return pHead1;
else{
pHead1=pHead1->next;
pHead2=pHead2->next;
}
return NULL;
}

int GetLength(ListNode* pHead){
int length=0;
while(pHead!=NULL){
length++;
pHead=pHead->next;
}
return length;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: