49 lines
1.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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;
}