nikunjsoni

25

Mar 21st, 2021
87
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode() : val(0), next(nullptr) {}
  7.  *     ListNode(int x) : val(x), next(nullptr) {}
  8.  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  9.  * };
  10.  */
  11. class Solution {
  12. public:
  13.    
  14.     ListNode* reverse(ListNode* start, ListNode* end){
  15.         while(start != end){
  16.             ListNode* tmp = start;
  17.             start = start->next;
  18.             tmp->next = end->next;
  19.             end->next = tmp;
  20.         }
  21.         return start;
  22.     }
  23.    
  24.     ListNode* reverseKGroup(ListNode* head, int k) {
  25.         ListNode *dummy = new ListNode(0, head);
  26.         ListNode *prev, *curr;
  27.         prev = dummy; curr = prev->next;
  28.        
  29.         int i = 0;
  30.         while(curr){
  31.             i++;
  32.             if(i == k){
  33.                 ListNode* last = prev->next;
  34.             ListNode* tmp = curr->next;
  35.                 prev->next = reverse(prev->next, curr);
  36.                 i=0;
  37.                 last->next = tmp;
  38.                 curr = prev = last;
  39.             }
  40.             curr = curr->next;
  41.         }
  42.         return dummy->next;
  43.     }
  44. };
RAW Paste Data