您的位置:首页 > Web前端 > HTML5

leetcode Ch5-Linked List

2015-07-24 20:25 531 查看
一、

1. Remove Duplicates from Sorted List II

class Solution {
public:
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
ListNode* p = pHead1;
int count1 = 0, count2 = 0;
while (p != NULL) {
count1++;
p = p->next;
}
p = pHead2;
while (p != NULL) {
count2++;
p = p->next;
}
if (count1 < count2) {
return findNode(pHead1, count1, pHead2, count2);
} else {
return findNode(pHead2, count2, pHead1, count1);
}
}

ListNode* findNode(ListNode* pHead1, int count1, ListNode* pHead2, int count2) {
if (pHead1 == NULL) {
return NULL;
}
int tmp = count2 - count1;
ListNode* p2 = pHead2, *p1 = pHead1;
while (tmp--) {
p2 = p2->next;
}
while (p1 != NULL && p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};


View Code
参考剑指offer P193. 本题说的“公共节点”不是指“值相等”,而是“同一个节点”。即两链表在该点处汇合。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: