Simple C++ solution using stack


  • 0
    B
    ListNode* reverseKGroup(ListNode* head, int k) {
    	ListNode * pre, * tmp;
    	pre = head;
    	tmp = pre;
    	stack<int> st;
    	bool stop = false;
    	while (pre != NULL)
    	{
    		tmp = pre;
    		for (int i = 0; i < k; i++)
    		{
    			if (tmp != NULL)
    			{
    				st.push(tmp->val);
    				tmp = tmp->next;
    			}
    			else
    			{
    				stop = true;
    				break;
    				
    			}
    		}
    		if (stop == true)
    		{
    			break;
    		}
    		tmp = pre;
    		for (int i = 0; i < k; i++)
    		{
    			tmp->val = st.top();
    			st.pop();
    			tmp = tmp->next;
    		}
    		pre = tmp;
    	}
    	return head;
    }
    

Log in to reply
 

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