Skip to content

链表的中间结点

LeetCode-876

给定一个头结点为 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。

js
var middleNode = function(head) {
  // 遍历链表,返回中间节点
  // let arr = []
  // while(head) {
  // arr.push(head)
  // head = head.next
  // }
  // return arr[parseInt(arr.length/2)]

  // 快慢指针,返回中间节点
  // 慢指针走一步,快指针走两步. 快指针走完,慢指针走完一半,即中间节点位置
  let slow = head
  let fast = head
  while(fast && fast.next) {
    fast = fast.next.next
    slow = slow.next
  }
  return slow
}