Skip to content
This repository has been archived by the owner on Dec 2, 2024. It is now read-only.

Commit

Permalink
sync
Browse files Browse the repository at this point in the history
  • Loading branch information
smokeriu committed Mar 30, 2022
1 parent 39c1ac6 commit 1f3f50f
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/s101/Test160.scala
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
}
}
25 changes: 25 additions & 0 deletions src/s801/Test876.scala
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
}

}
}

0 comments on commit 1f3f50f

Please sign in to comment.