diff --git a/Linked List/Reverse Nodes in k-group.cpp b/Linked List/Reverse Nodes in k-group.cpp new file mode 100644 index 0000000..fd0ea1f --- /dev/null +++ b/Linked List/Reverse Nodes in k-group.cpp @@ -0,0 +1,40 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + + ListNode* cursor = head; + for(int i = 0; i < k; i++){ + if(cursor == nullptr) return head; + cursor = cursor->next; + } + ListNode* curr=head; + ListNode* prev=NULL; + ListNode* forward=NULL; + int count=0; + while(curr!=NULL && countnext; + curr->next=prev; + prev=curr; + curr=forward; + count++; + + } + if(forward!=NULL) + { + head->next=reverseKGroup(forward,k); + } + + return prev; + } +}; \ No newline at end of file