Created
May 5, 2026 19:36
-
-
Save tatsuyax25/461ae09b1bb5b39fd1fdcd8b4b08645a to your computer and use it in GitHub Desktop.
Given the head of a linked list, rotate the list to the right by k places.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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} | |
| */ | |
| var rotateRight = function(head, k) { | |
| if (!head || !head.next || k === 0) return head; | |
| // 1. Find length and tail | |
| let n = 1; | |
| let tail = head; | |
| while (tail.next) { | |
| tail = tail.next; | |
| n++; | |
| } | |
| // 2. Make it circular | |
| tail.next = head; | |
| // 3. Reduce k | |
| k = k % n; | |
| let stepsToNewTail = n - k - 1; | |
| // 4. Find new tail | |
| let newTail = head; | |
| for (let i = 0; i < stepsToNewTail; i++) { | |
| newTail = newTail.next; | |
| } | |
| // 5. Break the circle | |
| let newHead = newTail.next; | |
| newTail.next = null; | |
| return newHead; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment