在做這道題時,首先想到的解法是遍歷第一個鏈表,將其全部添加到哈希表中,然后遍歷第二個鏈表,如果能夠再哈希表中查到元素,則返回這個元素,否則返回NULL。
但在實際寫代碼時,第一次寫默認為鏈表相交的判定條件是值相等,因此代碼寫成了這樣:
/*** 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_set<int> set;auto cur = headA;while(cur != NULL){set.insert(cur->val);cur = cur->next;}auto tmp = headB;while(tmp != NULL){if(set.find(tmp->val) != set.end() && set.find(tmp->next->val) != set.end()){return tmp;}tmp = tmp->next;}return NULL; }
};
intersectVal = 8,headA = [4,1,8,4,5], headB = [5,0,1,8,4,5], skipA = 2, skipB = 3;
在測試這個案例時,如果判定條件為數值相等,那么intersectVal = 1才對,而實際因為8,因此需要對判定條件進行修改,修改后的代碼如下:
/*** 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_set<ListNode*> set;auto cur = headA;while(cur != NULL){set.insert(cur);cur = cur->next;}auto tmp = headB;while(tmp != NULL){if(set.find(tmp) != set.end()){return tmp;}tmp = tmp->next;}return NULL;}
};
記錄一下佬的寫法,看個直呼精彩:
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {ListNode *A = headA, *B = headB;while (A != B) {A = A != nullptr ? A->next : headB;B = B != nullptr ? B->next : headA;}return A;}
};作者:Krahets
鏈接:https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/solutions/1190240/mian-shi-ti-0207-lian-biao-xiang-jiao-sh-b8hn/
來源:力扣(LeetCode)