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)
最新推荐文章于 2024-08-14 15:48:50 发布