孙晓聪
  • 最新
  • 博客
  • 书评
  • Reverse 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 reverseList = function (head) {
      if (!head) {
        return head
      }
    
      let prev = null
      let cursor = head
    
      while (cursor.next) {
        let next = cursor.next
        cursor.next = prev
    
        prev = cursor
        cursor = next
      }
    
      cursor.next = prev
      return cursor
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(1)

    Refined Version

    /**
     * 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 reverseList = function (head) {
      let prev = null
      let cur = head
    
      while (cur) {
        let next = cur.next
        cur.next = prev
    
        prev = cur
        cur = next
      }
    
      return prev
    }
    
    • Time Complexity: O(n)
    • Space Complexity: O(1)