acwing 66. 兩個鏈表的第一個公共結點

地址 https://www.acwing.com/problem/content/description/62/spa

輸入兩個鏈表,找出它們的第一個公共結點。code

當不存在公共節點時,返回空節點。blog

樣例

給出兩個鏈表以下所示:
A:        a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

輸出第一個公共節點c1

 

解法1  ip

因爲確定兩個鏈表頭有交集get

那麼每次移動兩個鏈表頭一步,若是移到鏈表尾則跳轉到另外一個鏈表表頭繼續移動。it

最後相交的位置就是第一個公共節點io

class Solution {
public:
    ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
        auto p = headA,q = headB;
        while(q != p ){
            if( q) q = q -> next;
            else q = headA;
            if(p ) p = p -> next;
            else p = headB;
        }
        return p ;
    }
};

解法2  使用哈希表記錄節點 每次移動進行查詢 第一個重合的就是公共節點class

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
        ListNode* p = headA;
        set<ListNode*> sp;
        while(p != NULL){
            sp.insert(p);
            p = p->next;
        }
        p= headB;
        while(p != NULL){
            if(sp.count(p) != 0) return p;
            p = p->next;
        }
        
        return NULL;
    }
};
相關文章
相關標籤/搜索