Rotate List
You get the head of a linked list and a number k. Turn the list to the right k times: each turn moves the last node to the front. Return the new head. Our example: 3 → 8 → 1 → 6 → 4, k = 7 — the answer is 6 → 4 → 3 → 8 → 1.
- input
head: the head of a linked list, maybe empty;k: by how many places to rotate it right.- returns
- The head of the list rotated right by
k: at each place, its last node moves to the front. - constraints
- 0 ≤ nodes ≤ 500
- −100 ≤ Node.val ≤ 100
- 0 ≤ k ≤ 2 · 10⁹
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* 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) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more fast and slow pointers problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.