leetcode-相交連結串列-15
阿新 • • 發佈:2021-02-01
題目要求
編寫一個程式,找到兩個單鏈表相交的起始節點。
思路
先計算兩個連結串列的長度,如果兩個連結串列結束的結點不一樣,肯定不是相交連結串列,如果結束結點一樣,那肯定相交,計算兩個連結串列長度的差值,讓長的先走差值步,然後兩個連結串列同時向下走,進行比較,第一個相等的結點就是兩個連結串列相交的起始結點。
圖解
程式碼實現
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { int lenA = 0, lenB = 0; struct ListNode* curA = headA; struct ListNode* curB = headB; while (curA) { curA = curA->next; lenA++; } while (curB) { curB = curB->next; lenB++; } if (curA != curB) { return NULL; } int n = abs(lenA - lenB); curA = headA; curB = headB; while (n--) { if (lenA > lenB) { curA = curA->next; } if (lenA < lenB) { curB = curB->next; } } while (curA != curB) { curA = curA->next; curB = curB->next; } return curA; }