Untitled

mail@pastecode.io avatar
unknown
plain_text
23 days ago
924 B
1
Indexable
Never
/**
 * 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* rev(ListNode* first,ListNode* end){ //reverses a list and returns beginning of the reversed list
        ListNode* prev=end;
        while(first!=end){
            ListNode* tmp=first->next;
            first->next=prev;
            prev=first;
            first=tmp;
        }
        return prev;
    }

    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* node=head;
        for(int i=0;i<k;i++){
            if(node==NULL) return head;
            node=node->next;
        }
        ListNode* new_head=rev(head,node);
        head->next=reverseKGroup(node,k);
        return new_head;
    }
};
Leave a Comment