Short c++ iterative solution using pointer-to-pointer!


  • 0
    X
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            ListNode** pp=&head;
            ListNode* ghead=*pp;//ghead is the group head
            while(1){
                int len=k;
                while(len){
                    if(ghead==NULL) return head;
                    ghead=ghead->next;
                    len--;
                }
                ListNode* curr=*pp,*pnext=NULL;
                while(curr->next!=ghead){
                    pnext=curr->next;
                    curr->next=pnext->next;
                    pnext->next=*pp;
                    (*pp)=pnext;
                }
                pp=&(curr->next);
            }
            return head;
        }
    };

  • 0
    A

    @xinqrs Not efficient. For every k-group, you algorithm does k-1 times of switch. Actually, we only need k/2 times of switch.


Log in to reply
 

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