From 6992735d8de6d1875d0565413faed410e81c822e Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Thu, 12 May 2022 12:46:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E9=9D=A2=E8=AF=95?= =?UTF-8?q?=E9=A2=9802.07.=E9=93=BE=E8=A1=A8=E7=9B=B8=E4=BA=A4.md=20Scala?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 50 ++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index 2e7226de..0a38cc33 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -317,7 +317,55 @@ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { } ``` - +Scala: +```scala +object Solution { + def getIntersectionNode(headA: ListNode, headB: ListNode): ListNode = { + var lenA = 0 // headA链表的长度 + var lenB = 0 // headB链表的长度 + var tmp = headA // 临时变量 + // 统计headA的长度 + while (tmp != null) { + lenA += 1; + tmp = tmp.next + } + // 统计headB的长度 + tmp = headB // 临时变量赋值给headB + while (tmp != null) { + lenB += 1 + tmp = tmp.next + } + // 因为传递过来的参数是不可变量,所以需要重新定义 + var listA = headA + var listB = headB + // 两个链表的长度差 + // 如果gap>0,lenA>lenB,headA(listA)链表往前移动gap步 + // 如果gap<0,lenA 0) { + // 因为不可以i-=1,所以可以使用for + for (i <- 0 until gap) { + listA = listA.next // 链表headA(listA) 移动 + } + } else { + gap = math.abs(gap) // 此刻gap为负值,取绝对值 + for (i <- 0 until gap) { + listB = listB.next + } + } + // 现在两个链表同时往前走,如果相等则返回 + while (listA != null && listB != null) { + if (listA == listB) { + return listA + } + listA = listA.next + listB = listB.next + } + // 如果链表没有相交则返回null,return可以省略 + null + } +} +``` -----------------------