My C++ solution


  • 0
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            if (!head || !head->next || !k ||!(k-1)) return head;
    		int len = 0;
    		ListNode* temp = head;
    		while (temp){ ++len; temp = temp->next; }
    		ListNode* front = new ListNode(0);
    		front->next = head;
    		head = front;                                 // insert head node
    		ListNode* Khead = head;
    		int	LOL_cool = len / k;
    		while (LOL_cool--){
    			ListNode* Shead = Khead->next;
    			ListNode*  post = Khead->next;
    			ListNode*  prev = post->next;
    			for (int i = 0; i < k-1; i++){
    				temp = prev->next;
    				post->next = prev->next;
    				prev->next = Khead->next;
    				Khead->next = prev;
    				prev = temp;
    			}
    			Khead = Shead;
    		}
    		return front->next;
        }
    };

Log in to reply
 

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