From e662df7c0c602f90f9cdc129c71b709dfdeb3337 Mon Sep 17 00:00:00 2001 From: bqlin Date: Fri, 10 Dec 2021 17:19:39 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=9802.07.=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9B=B8=E4=BA=A4=EF=BC=9A=E5=A2=9E=E5=8A=A0C?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) 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; +} +``` +