您的位置:首页 > Web前端

【剑指offer】输入两个链表,找出它们的第一个公共结点。

2015-09-14 17:30 447 查看
思路:分别遍历一遍,得到长度差,然后长的先走这个差值,然后在一起走,知道第一个相同的为止。

/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
if(pHead1 == NULL || pHead2 == NULL)
return NULL;
int length1 = 0;
int length2 = 0;
ListNode *pNode1 = pHead1;
while(pNode1 != NULL){
++length1;
pNode1 = pNode1->next;
}
ListNode *pNode2 = pHead2;
while(pNode2 != NULL){
++length2;
pNode2 = pNode2->next;
}
pNode1 = pHead1;
pNode2 = pHead2;
if(length1 > length2){
int diff = length1 - length2;
while(diff-- > 0){
pNode1 = pNode1->next;
}
}
if(length1 < length2){
int diff = length2 - length1;
while(diff-- > 0){
pNode2 = pNode2->next;
}
}
ListNode *pCommonNode = pNode1;
while(pNode1 != pNode2 && pNode1 != NULL && pNode2 != NULL){
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
pCommonNode = pNode1;
return pCommonNode;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: