Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6992735

Browse files
committed
添加 面试题02.07.链表相交.md Scala版本
1 parent 5fd8521 commit 6992735

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

‎problems/面试题02.07.链表相交.md

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,55 @@ ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
317317
}
318318
```
319319
320-
320+
Scala:
321+
```scala
322+
object Solution {
323+
def getIntersectionNode(headA: ListNode, headB: ListNode): ListNode = {
324+
var lenA = 0 // headA链表的长度
325+
var lenB = 0 // headB链表的长度
326+
var tmp = headA // 临时变量
327+
// 统计headA的长度
328+
while (tmp != null) {
329+
lenA += 1;
330+
tmp = tmp.next
331+
}
332+
// 统计headB的长度
333+
tmp = headB // 临时变量赋值给headB
334+
while (tmp != null) {
335+
lenB += 1
336+
tmp = tmp.next
337+
}
338+
// 因为传递过来的参数是不可变量,所以需要重新定义
339+
var listA = headA
340+
var listB = headB
341+
// 两个链表的长度差
342+
// 如果gap>0,lenA>lenB,headA(listA)链表往前移动gap步
343+
// 如果gap<0,lenA<lenB,headB(listB)链表往前移动-gap步
344+
var gap = lenA - lenB
345+
if (gap > 0) {
346+
// 因为不可以i-=1,所以可以使用for
347+
for (i <- 0 until gap) {
348+
listA = listA.next // 链表headA(listA) 移动
349+
}
350+
} else {
351+
gap = math.abs(gap) // 此刻gap为负值,取绝对值
352+
for (i <- 0 until gap) {
353+
listB = listB.next
354+
}
355+
}
356+
// 现在两个链表同时往前走,如果相等则返回
357+
while (listA != null && listB != null) {
358+
if (listA == listB) {
359+
return listA
360+
}
361+
listA = listA.next
362+
listB = listB.next
363+
}
364+
// 如果链表没有相交则返回null,return可以省略
365+
null
366+
}
367+
}
368+
```
321369

322370

323371
-----------------------

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /