https://leetcode-cn.com/problems/middle-of-the-linked-list/
object Solution {
/**
* 暴力遍历求解
*/
def middleNode(head: ListNode): ListNode = {
val len = getLength(head)
var cur = head
for(i<-0 until(len/2)){
cur = cur.next
}
cur
}
def getLength(head:ListNode)={
var cur = head
var count = 0
while(cur != null){
count +=1
cur = cur.next
}
count
}
/**
* 快慢指针求解
*/
def middleNode(head: ListNode): ListNode = {
var slow = head
var fast = head
while(fast != null && fast.next != null){
slow = slow.next
fast = fast.next.next
}
slow
}
}
Scala 实现寻找链表中间元素(leetCode 876)
最新推荐文章于 2025-11-24 01:23:29 发布
这篇博客介绍了两种方法解决LeetCode上的链表中点问题。第一种是暴力遍历,通过计算链表长度并遍历一半长度找到中点;第二种是采用快慢指针技巧,快指针每次前进两步,慢指针每次前进一步,当快指针到达链表尾部时,慢指针即位于链表中点。
1910

被折叠的 条评论
为什么被折叠?



