Simple and intuitive solution for reversing a linklist


  • 0
    N
    
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            int l = 0;
            ListNode *temp = head;
            while(temp){
                l++;
                temp = temp->next;
            }
            int p = l%k;
            int q = l/k;
            temp = head;
            ListNode *curr=head,*newhead = NULL,*prend = NULL;
            int cnt = 0;
            while(q--){
                ListNode *end = curr;
                ListNode *nxt = NULL,*pre = NULL;
                while(curr){
                    if(cnt==k)  break;
                    cnt++;
                    nxt = curr->next;
                    curr->next = pre;
                    pre = curr;
                    curr = nxt;
                }
                cnt = 0;
                if(newhead==NULL){
                    newhead = pre;
                    prend = head;
                }else{
                    prend->next = pre;
                    prend = end;
                }
            }
            if(prend == NULL)   return head;
            else{
                prend->next = curr;
            }
            return newhead;
        }
    };
    
    

Log in to reply
 

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