孙晓聪
  • 最新
  • 博客
  • 书评
  • Middle of the Linked List

    Description

    doc

    Solutions

    First Idea

    /**
     * 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 cur = head
    
      while (cur !== null) {
        count++
        cur = cur.next
      }
    
      let middle = Math.floor(count / 2)
      cur = head
      while (middle > 0) {
        cur = cur.next
        middle--
      }
    
      return cur
    }
    

    -- Time Complexity: O(n) -- Space Complexity: O(1)

    Two Pointers

    /**
     * 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 slow = (fast = head)
    
      while (fast) {
        fast = fast.next
        if (!fast) {
          break
        }
    
        fast = fast.next
        slow = slow.next
      }
    
      return slow
    }
    

    -- Time Complexity: O(n) -- Space Complexity: O(1)