diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index e3c284c0..9d399ef9 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -249,6 +249,45 @@ var getIntersectionNode = function(headA, headB) { }; ``` +C: + +```c +ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode *l = NULL, *s = NULL; + int lenA = 0, lenB = 0, gap = 0; + // 求出两个链表的长度 + s = headA; + while (s) { + lenA ++; + s = s->next; + } + s = headB; + while (s) { + lenB ++; + s = s->next; + } + + // 求出两个链表长度差 + if (lenA > lenB) { + l = headA, s = headB; + gap = lenA - lenB; + } else { + l = headB, s = headA; + gap = lenB - lenA; + } + + // 尾部对齐 + while (gap--) l = l->next; + // 移动,并检查是否有相同的元素 + while (l) { + if (l == s) return l; + l = l->next, s = s->next; + } + + return NULL; +} +``` +