/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * https://leetcode.cn/problems/rotate-list/?envType=study-plan-v2&envId=top-interview-150 * @param {ListNode} head * @param {number} k * @return {ListNode} */ /* 思路:观察发现,旋转1,就等于将链表首位相连,从原头节点出发,走 n-2 步,之后断开这个节点后后面 的节点连接即可,例如1->2->3,roate1就是3->1->2,来一个长一点的例子1->2->3->4->5->6,我们假设 要roate4,想象6->1是首位相连的,从原头节点1开始往后走n-4-1也就是1步,到达2的位置,这个时候记录 2.next作为返回的头节点,并且把它断开,就变成了3->4->5->5->1->2,这就是我们要的结果 */ const rotateRight = function (head, k) { }; function f1(head, k) { if (head === null || head.next === null) return head; // 没有节点,或者只有一个节点,直接返回 // 1.遍历链表获取尾节点,和节点个数 let tail = head; let len = 1; while (tail.next) { len++; tail = tail.next; } // 2.把链表首尾相连 tail.next = head; // 3.从head往后走n-k-1步,找到要断开的位置 tail = head; k %= len; // 当k比链表长度还长时需取模操作,比如len=3,要旋转4,那么效果和旋转1是一样的 for (let i = 0, setp = len - k - 1; i < setp; i++) { tail = tail.next; } // 4.保留tail的next作为新节点的头节点,然后断开 const rHead = tail.next; tail.next = null; return rHead; }