876. 链表的中间结点
https://leetcode-cn.com/problems/middle-of-the-linked-list/
问题描述
问题分析
代码实现
js
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var middleNode = function(head) {
let count = 0
let temp = head
while(temp) {
count++
temp = temp.next
}
for(let i = 0; i < (count-1)/2; i++) {
head = head.next
}
return head
};
java
class Solution {
public ListNode middleNode(ListNode head) {
if (head.next == null) return head;
if (head.next.next == null) return head.next;
ListNode slow = head.next;
ListNode fast = head.next.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == null) return slow;
}
return slow;
}
}