Reverse Nodes in k-Group Problem


Description

LeetCode Problem 25.

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example 1:

1
2
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2:

1
2
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

Example 3:

1
2
Input: head = [1,2,3,4,5], k = 1
Output: [1,2,3,4,5]

Example 4:

1
2
Input: head = [1], k = 1
Output: [1]

Constraints:

  • The number of nodes in the list is in the range sz.
  • 1 <= sz <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= sz


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int length(ListNode * node){
    int count=0;
    while(node){
        count++;
        node=node->next;
    }
    return count;
}
ListNode* reverseKGroup(ListNode* head, int k) {
   if (length(head) < k)return head;
   ListNode * cur=head;
   ListNode * prev=NULL, *next=NULL;
   while (int i=0; i < k; i++){
       next=cur->next;
       cur->next=prev;
       prev=cur;
       cur=next;
   }
   head->next=reverseKGroup(cur, k);
   return prev;
 }
};




Related Posts

Middle Of The Linked List Problem

LeetCode 876. Given the head of a singly linked list,...

Linked List Components Problem

LeetCode 817. You are given the head of a linked...

Split Linked List In Parts Problem

LeetCode 725. Given the head of a singly linked list...

All O'One Data Structure Problem

LeetCode 432. Design a data structure to store the strings...

Add Two Numbers II Problem

LeetCode 445. You are given two non-empty linked lists representing...