找到兩個單鏈表的共同節點.
舉例來說, 下面兩個鏈表A和B:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
共同節點爲c1.
分析:
共同節點距離A,B的起點headA, headB的距離差爲定值, 等於它們的各自總長的差值, 我們只需要求出這個差值, 把兩個鏈表的頭移動到距離c1相等距離的起點處即可.
代碼:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int deltaLength = getLengthOfList(headA) - getLengthOfList(headB); // A > B if (deltaLength > 0) { while (deltaLength-- > 0) headA = headA->next; } // A < B else if (deltaLength < 0) { while (deltaLength++ < 0) headB = headB->next; } // now A and B has the same distance to intersection node while (NULL != headA && NULL != headB) { if (headA == headB) return headA; headA = headA->next; headB = headB->next; } return NULL; } int getLengthOfList(ListNode *head) { int res = 0; while (NULL != head) { res++; head = head->next; } return res; } };