剑指offer:两个链表的第一个公共结点

来源:互联网 发布:hit韩服数据 编辑:程序博客网 时间:2024/05/28 04:53

题目描述

输入两个链表,找出它们的第一个公共结点。

/*struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};*/class Solution {public:    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {        int size1 = getLength(pHead1);int size2 = getLength(pHead2);if (size1 == 0 || size2 == 0)return NULL;int longer = size1 - size2;if (size1 > size2){for (int i = 0; i < longer; ++i)pHead1 = pHead1->next;}else if (size1 < size2){for (int i = 0; i < -longer; ++i)pHead2 = pHead2->next;}while (pHead1 != NULL && pHead2 != NULL){if (pHead1 == pHead2)return pHead1;pHead1 = pHead1->next;pHead2 = pHead2->next;}return NULL;    }        int getLength(ListNode* pHead){int l=0;while (pHead != NULL){pHead = pHead->next;    l++;}return l;}};


0 0
原创粉丝点击