160. Intersection of Two Linked Lists

1.問題

  • 返回開始重複的node

2.想法

  • 用map紀錄s出現過的node, 再看看t是否有出現相同的node

3.程式碼

/**
 * 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) {
        unordered_map<ListNode*, int> m;
        ListNode *head = headA;
        while (head)
        {
            m[head] = 1;
            head = head->next;
        }
        
         head = headB;
         while (head)
         {
            if (m.find(head) != m.end())
            {
                return head;
            }
            head = head->next;
         }
        return NULL;
        
    }
};

4.Performance

Last updated