forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse Nodes in k-Group.cpp
46 lines (42 loc) · 1.35 KB
/
Reverse Nodes in k-Group.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Contributed by:
Name: Abhijai Rajawat
University: VIT, Vellore
Github: www.github.com/Severus25
// Problem Statement:
Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
// Problem Solution:
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(head==NULL||k==1) return head;
int num=0;
ListNode *preheader = new ListNode(-1);
preheader->next = head;
ListNode *cur = preheader, *nex, *tmp, *pre = preheader;
while(cur = cur->next)
num++;
while(num>=k) {
cur = pre->next;
nex = cur->next;
for(int i=1;i<k;i++) {
tmp= nex->next;
nex->next = pre->next;
pre->next = nex;
cur->next = tmp;
nex = tmp;
}
pre = cur;
num-=k;
}
return preheader->next;
}
};