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

[pull] master from youngyangyang04:master #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 9 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
May 30, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
添加 面试题02.07.链表相交.md Scala版本
  • Loading branch information
wzqwtt committed May 12, 2022
commit 6992735d8de6d1875d0565413faed410e81c822e
50 changes: 49 additions & 1 deletion problems/面试题02.07.链表相交.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -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<lenB,headB(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
}
// 如果链表没有相交则返回null,return可以省略
null
}
}
```


-----------------------
Expand Down

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