This repository has been archived by the owner on Dec 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package s101 | ||
|
||
import util.ListNode | ||
|
||
object Test160 { | ||
def getIntersectionNode(headA: ListNode, headB: ListNode): ListNode = { | ||
// 如果第一个节点即为相交节点,则直接返回 | ||
if (headA == headB) return headA | ||
|
||
var pa = headA | ||
var pb = headB | ||
|
||
var aLen = 0 | ||
var bLen = 0 | ||
|
||
// 想让pa,pb遍历到底,计算长度。 | ||
while (pa.next != null) { | ||
pa = pa.next | ||
aLen += 1 | ||
} | ||
|
||
while (pb.next != null) { | ||
pb = pb.next | ||
bLen += 1 | ||
} | ||
|
||
// 得到两个链表的长度差距 | ||
val diff = aLen - bLen | ||
pa = headA | ||
pb = headB | ||
if (diff < 0) { | ||
// 链表b更长, 是b向后移-diff次 | ||
for (elem <- 0.until(diff, -1)) { | ||
pb = pb.next | ||
} | ||
} else if (diff > 0) { | ||
// 链表a更长 | ||
for (elem <- 0.until(diff)) { | ||
pa = pa.next | ||
} | ||
} else { | ||
// 一样长,不做处理 | ||
} | ||
|
||
while (pa != pb && pa != null && pb != null) { | ||
pa = pa.next | ||
pb = pb.next | ||
} | ||
pa | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package s801 | ||
|
||
import util.ListNode | ||
|
||
object Test876 { | ||
def middleNode(head: ListNode): ListNode = { | ||
// 快指针一次走两步,慢指针一次走一步 | ||
var slow = head | ||
var fast = head | ||
while (fast.next != null && fast.next.next != null) { | ||
// fast的后两位都不是null,则其可以向后移动 | ||
slow = slow.next | ||
fast = fast.next.next | ||
} | ||
|
||
if (fast.next == null){ | ||
// 如果后一位为null,说明是奇数 | ||
slow | ||
}else{ | ||
// 否则是偶数 | ||
slow.next | ||
} | ||
|
||
} | ||
} |