C++ solution, 30ms


  • 0
    Z
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            vector<int> record;
            ListNode *head_temp=head;
            ListNode *head_save=head;
            if(head_temp==NULL) return head;
            int count=0;
            
            while(head_temp!=NULL){
                record.push_back(head_temp->val);
                count++;
                head_temp=head_temp->next;
                if(count==k){
                    for(int j=0;j<k;j++){
                        head_save->val=record.back();
                        record.pop_back();
                        head_save=head_save->next;
                    }
                    count=0;
                }
            }
            return head;
        }
    };
    

    This solution altered the values of the nodes. The correct code should be(takes 28ms):

    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            ListNode *head_temp=head;
            ListNode *head_pre=NULL;
            ListNode *head_next=NULL;
            ListNode *head_old=head;
            ListNode *head_old2=head;
            int count=0;
            while(head_temp!=NULL){
                count++;
                head_temp=head_temp->next;
            }
            
            int l=count/k;
            
            head_temp=head;
            
            for(int i=0;i<l;i++){
                if(i>0)
                head_old2=head_temp;
                
                for(int j=0;j<k;j++){
                    head_next=head_temp->next;
                    head_temp->next=head_pre;
                    head_pre=head_temp;
                    head_temp=head_next;
                }
                if(i==0)
                head=head_pre;
                
                if(i>0){
                    head_old->next=head_pre;
                    head_old=head_old2;
                }
                if(i==l-1){
                    head_old2->next=head_next;
                }
            }
            return head;
        }
    };

  • 0
    A

    You may not alter the values in the nodes, only nodes itself may be changed.


  • 0
    Z

    Thank you for your reminding. I modified the solution.


Log in to reply
 

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