My simple c++ code (22ms)


  • 0
    W
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(k<=1||!head) return head;
            ListNode *start, *end, *new_head=new ListNode(0), *next_head, *pre_tail=new_head;
            new_head->next = head;
            int cnt;
            for(start=head, end=head->next, cnt=1; end||cnt==0; end=end->next, cnt=(cnt+1)%k){
                if(cnt==0){
                    next_head = helper(start, end);
                    pre_tail->next = next_head;
                    pre_tail = start;
                    start = end;
                }
                if(!end&&cnt==0) break;
            }
            return new_head->next;
        }
    private:
        ListNode* helper(ListNode* start, ListNode* end){
            ListNode *pre=end, *cur=start, *post=start->next;
            while(cur!=end){
                cur->next = pre;
                pre = cur;
                cur = post;
                if(post!=end)
                    post = post->next;
            }
            return pre;
        }
    };
    

Log in to reply
 

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