添加 面试题02.07.链表相交.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-12 12:46:47 +08:00
parent 5fd85215ea
commit 6992735d8d

View File

@ -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>0lenA>lenBheadA(listA)链表往前移动gap步
// 如果gap<0lenA<lenBheadB(listB)链表往前移动-gap步
var gap = lenA - lenB
if (gap > 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
}
// 如果链表没有相交则返回nullreturn可以省略
null
}
}
```
-----------------------