Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 1 KB

File metadata and controls

46 lines (35 loc) · 1 KB

Leetcode:206 反转链表

动画演示:

image-20210909173020663

image-20210910094316252

image-20210910094323761

image-20210910094448057

image-20210910094516178

image-20210910094829686

image-20210910094907052

/**
 * 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 pre = null;
  let cur = head;
  while(cur){
    const tmp = cur.next;
    cur.next = pre;
    pre = cur;
    cur = tmp;
  }
  return pre;
};

// 时间复杂度: O(n)
// 空间复杂度: O(1)