My accepted simple recursive solution in C++,Any advising?


  • 0
    K
    class Solution 
    {
    public:
        ListNode *reverseKGroup(ListNode *head, int k) 
    	{
    		ListNode* post=head;
    		ListNode* curPtr=post;
    		
    		//判断list的长度是否小于K
    		for(int i=0;i<k;i++)
    		{
    			curPtr=post;
    			if(NULL==curPtr)
    				return head;
    			post=post->next;
    		}
    		ListNode* preHead=new ListNode(0);
    		preHead->next=head;
    		ListNode* retHead=preHead;
    		post=head;
            for(int i=0;i<k;i++)
    		{  
    			curPtr=post;
    			post=post->next;
    			curPtr->next=preHead;
    			preHead=curPtr;
    		}
    		retHead->next->next=reverseKGroup(post,k);
    		return preHead;
    		
        }
    };

  • 0
    Q

    If you use recursion, the space complexity is no longer constant.


Log in to reply
 

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