my fast and easy to understand code


  • 0
    I

    The function reverseList will reverse the list from start to end.

    ListNode* reverseKGroup(ListNode* head, int k) {
    // k = 1, special case
    if (k == 1 || k == 0 || !head || !head->next)
    {
    return head;
    }
    // find the group and reverse each group
    int cnt = 1;
    ListNode *newHead = new ListNode(0);
    newHead->next = head;
    ListNode *curNode = head, *lastGroupNode = newHead;

    	while (curNode)
    	{
    		ListNode* startNode = curNode;
    		while (cnt%k != 0 && curNode)
    		{
    			curNode = curNode->next;
    			cnt++;
    		}
    		if (curNode)
    		{
    			ListNode * nextGroupStart = curNode->next;
    			reverseList(startNode, curNode);
    			lastGroupNode->next = curNode;
    			lastGroupNode = startNode;
    			cnt = 1;
    			curNode = nextGroupStart;
    		}
    		else
    		{
    			lastGroupNode->next = startNode;
    		}
    	}
    
    	// return newhead
    	return newHead->next;
    }
    void reverseList(ListNode *head, ListNode *end)
    {
    	if (head == end)
    	{
    		return;
    	}
    	// reverse the list
    	ListNode *lastNode = nullptr, *curNode = head, *temp, *stopNode = end->next;
    	while (curNode != stopNode)
    	{
    		temp = curNode->next;
    		curNode->next = lastNode;
    		lastNode = curNode;
    		curNode = temp;
    	}
    }

Log in to reply
 

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