160. 相交連結串列
阿新 • • 發佈:2018-12-18
編寫一個程式,找到兩個單鏈表相交的起始節點。
例如,下面的兩個連結串列:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
在節點 c1 開始相交。
注意:
- 如果兩個連結串列沒有交點,返回
null
. - 在返回結果後,兩個連結串列仍須保持原有的結構。
- 可假定整個連結串列結構中沒有迴圈。
- 程式儘量滿足 O(n) 時間複雜度,且僅用 O(1) 記憶體。
class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { std::set<ListNode*> node_set; while(headA){ node_set.insert(headA); headA = headA ->next; } while(headB){ if(node_set.find(headB) != node_set.end()){ return headB; } headB = headB -> next; } return NULL; } };