clean c++ solution


  • 0
    H
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(!head || !head->next || k == 1) return head;
            ListNode* new_head = new ListNode(0);
            new_head->next = head;
            ListNode* pre = new_head, * cur = new_head;
            int num = 0;
            while(cur = cur->next) num ++; // total number of nodes
            while(num >= k) {
                cur = pre->next;
                for(int i = 0; i < k-1; i ++) {
                    ListNode* nxt = cur->next;
                    cur->next = nxt->next;
                    nxt->next = pre->next;
                    pre->next = nxt;
                }
                pre = cur;
                num -= k;
            }
            return new_head->next;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.