Skip to content

Latest commit

 

History

History
44 lines (38 loc) · 1.34 KB

61-旋转链表.md

File metadata and controls

44 lines (38 loc) · 1.34 KB

61-旋转链表

难度中等

原题地址-参考 给你一个链表的头节点 head ,将链表每个节点向右移动 k 个位置。

步骤 1:获取链表中元素的个数 length
步骤 2:将链表连成环,最后一个 node 的 node.next = head
步骤 3:移动 length - step 个 node 为 node.next
步骤 4:然后在 node 那断开环

const rotateRight = function (head, k) {
  if (!head || !head.next) return head;
  let length = 1;
  let cur = head;
  while (cur.next) {
    cur = cur.next;
    length++;
  }
  // 当 k 大于 长度时,又是一轮循环,所以对长度取余 10 % 3 = 1
  let step = k % length;
  cur.next = head; // 形成环
  let node = head;
  let index = 1;
  // 重点还是在这里
  // 如果 length = 5, step = 2,那么 node = node.next,那么就需要把前2个的node换成是node.next
  // 然后在 node 那断开,就是新的链表了,牛逼牛逼
  while (index < length - step) {
    node = node.next;
    index++;
  }
  let vnode = node.next;
  node.next = null;
  return vnode;
};

旋转链表和反转链表是不是一样的,如果是,那就是,那不就是可以根据 while 来进行了

while (curr) { [curr.next, prev, curr] = [curr.next, curr, pre] }