Reverse Nodes in k-Group
You get a linked list and a number k. Reverse the nodes in groups of k: the first k, then the next k, and so on. If fewer than k nodes are left at the end, they keep their order. Only links may change, not the values. Our example: 4 → 1 → 7 → 3 → 9 → 2 → 8 → 5, k = 3 — the answer is 7 → 1 → 4 → 2 → 9 → 3 → 8 → 5.
- input
head: the head of a linked list ofnnodes;k: the size of a group.- returns
- The head of the list with every
knodes in a row reversed, from its start; the nodes left at the end, fewer thank, stay as they are. - constraints
- 1 ≤ n ≤ 1000
- 1 ≤ k ≤ n
- 0 ≤ Node.val ≤ 1000
- 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 reverseKGroup(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 linked list 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.