leetcode 61题

Posted by franki on June 24, 2021

leetcode 61题 旋转链表

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例1

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例2

输入:head = [0,1,2], k = 4
输出:[2,0,1]

思路

通过求余的方式,确定最终反转的位置

代码

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
function rotateRight(head, k) {
  if (head === null || head.next === null || k === 0) {
    return head;
  }
  let newHead = new ListNode(0);
  newHead.next = head;
  let len = 0;
  let cur = newHead;
  while (cur.next) {
    len++;
    cur = cur.next;
  }
  if (k % len === 0) {
    return head;
  }
  cur.next = head;
  cur = newHead;
  for (let i=len-k%len; i>0; i--) {
    cur = cur.next;
  }
  const res = new ListNode(0);
  res.next = cur.next;
  cur.next = null;
  return res.next;
}

复杂度分析:

  • 时间复杂度: O(N)
  • 空间复杂度:O(N)