|
| 1 | +/*Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. |
| 2 | +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. |
| 3 | +You may not alter the values in the list's nodes, only nodes themselves may be changed. |
| 4 | +
|
| 5 | +Example : |
| 6 | +
|
| 7 | + 1 ---> 2 ---> 3 ---> 4 ---> 5 |
| 8 | + |
| 9 | + becomes |
| 10 | + |
| 11 | + 2 ---> 1 ---> 4 ---> 3 ---> 5 |
| 12 | + |
| 13 | + |
| 14 | +Input: head = [1,2,3,4,5], k = 2 |
| 15 | +Output: [2,1,4,3,5] |
| 16 | +
|
| 17 | +Follow-up: Can you solve the problem in O(1) extra memory space? |
| 18 | +*/ |
| 19 | + |
| 20 | +#include <bits/stdc++.h> |
| 21 | +using namespace std; |
| 22 | + |
| 23 | +struct ListNode |
| 24 | +{ |
| 25 | + int val; |
| 26 | + ListNode *next; |
| 27 | + ListNode(int n) |
| 28 | + { |
| 29 | + val = n; |
| 30 | + next = NULL; |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +void printList(ListNode* head){ |
| 35 | + int i = 0; |
| 36 | + while(head){ |
| 37 | + cout<<head->val<<" "; |
| 38 | + head = head->next; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +ListNode* reverseKGroup(ListNode* head, int k) { |
| 43 | + ListNode* curr = head; |
| 44 | + int count = 0; |
| 45 | + |
| 46 | + //Take first k group of nodes |
| 47 | + while (curr != NULL && count != k) { |
| 48 | + curr = curr->next; |
| 49 | + count++; |
| 50 | + } |
| 51 | + |
| 52 | + if (count == k) { |
| 53 | + //Recursively taking all k group of nodes |
| 54 | + //Passing next group first node as curr |
| 55 | + curr = reverseKGroup(curr, k); |
| 56 | + |
| 57 | + //Go on reversing the node group using normal reverse steps |
| 58 | + while (count-- > 0) { |
| 59 | + ListNode* tmp = head->next; |
| 60 | + head->next = curr; |
| 61 | + curr = head; |
| 62 | + head = tmp; |
| 63 | + } |
| 64 | + head = curr; |
| 65 | + } |
| 66 | + return head; |
| 67 | +} |
| 68 | + |
| 69 | +int main() |
| 70 | +{ |
| 71 | + int NumOfNodes, nn, data, k; |
| 72 | + cin>>NumOfNodes; |
| 73 | + nn = NumOfNodes; |
| 74 | + ListNode* head = NULL; |
| 75 | + ListNode* tail = head; |
| 76 | + |
| 77 | + while(nn--){ |
| 78 | + cin>>data; |
| 79 | + if(!head){ |
| 80 | + head = new ListNode(data); |
| 81 | + tail = head; |
| 82 | + } |
| 83 | + else{ |
| 84 | + tail->next = new ListNode(data); |
| 85 | + tail = tail->next; |
| 86 | + } |
| 87 | + } |
| 88 | + cin>>k; |
| 89 | + ListNode* finalHead = reverseKGroup(head, k); |
| 90 | + printList(finalHead); |
| 91 | + return 0; |
| 92 | +} |
| 93 | +//No extra space used. |
| 94 | + |
0 commit comments