[leetcode]#160 Intersection of Two Linked Lists

3011 ワード

Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Your code should preferably run in O(n) time and use only O(1) memory. (1)O(1)空間とO(n)時間を用いて,2つのチェーンテーブルの共通部分の起点を探し出す
問題解決の構想:1、両者の長さを計算して、そして2つのチェーンテーブルの末端が同じかどうかを判断して、異なってnull 2を返して、チェーンテーブルの長さの比較的に長いのが(tailの数量-Btailの数量)歩まで歩かせて、それから短いチェーンテーブルと同期して下へ歩いて、出会った第1個の同じノードは最も早い公共ノードです
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode * tail = headA;
        ListNode * Btail = headB;
        int countA = 1, countB = 1, step;
        if (tail == NULL || headB == NULL)
            return NULL;
        while (tail->next != NULL) {
            tail = tail->next;
            countA++;
        }
        while (Btail->next != NULL) {
            Btail = Btail->next;
            countB++;
        }
        if (Btail != tail)
            return NULL;
        step = countA - countB;
        tail = headA;
        Btail = headB;
        if (step < 0) {
            step = -step;
            tail = headB;
            Btail = headA;
        }
        for (int i = 0;i < step; i++) {
            tail = tail->next;
        }
        while (tail != NULL && Btail != NULL && tail !=Btail) {
            tail = tail->next;
            Btail = Btail->next;
        }
        return tail;
    }
};