1. 程式人生 > >劍指offer---兩個鏈表的第一個公共結點

劍指offer---兩個鏈表的第一個公共結點

ext node col logs pan color while bus get

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution 
{
public:
    int Getlength(ListNode* pNode)
    {
        int length = 0;
        ListNode* A = pNode;
        while (A != NULL)
        {
            ++length;
            A 
= A->next; } return length; } ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) { int length1 = Getlength( pHead1); int length2 = Getlength( pHead2); int bushu = abs(length1 - length2); ListNode* curNode; ListNode
* firstCommonNode; if (length1 >= length2) { curNode = pHead1; while (bushu != 0) { curNode = curNode->next; --bushu; } while ((pHead2 != NULL) && (curNode != NULL) && (curNode != pHead2)) { pHead2
= pHead2->next; curNode = curNode->next; } firstCommonNode = curNode; return firstCommonNode; } else { curNode = pHead2; while (bushu != 0) { curNode = curNode->next; --bushu; } while ((pHead1 != NULL) && (curNode != NULL) && (curNode != pHead1)) { pHead1 = pHead1->next; curNode = curNode->next; } firstCommonNode = curNode; return firstCommonNode; } } };

劍指offer---兩個鏈表的第一個公共結點