My C++ solution 28ms


  • 0
    S
    ListNode* reverseKGroup(ListNode* head, int k) {
        stack<ListNode*> s;
    	int i,headflag=0;
    	ListNode *temp,*pre,*begin,*nextnode;
    	
    	if(head==NULL||k<1)
    		return head;
    	for(begin=pre=head;begin;){
    		for(i=0,temp=begin;i<k;i++){
    			if(!temp)
    				break;
    			else{
    				s.push(temp);
    				temp=temp->next;
    			}
    		}
    		nextnode=temp;
    		if(s.size()==k){
    			temp=begin=s.top();
    			s.pop();
    			while(!s.empty()){
    				temp->next=s.top();
    				temp=temp->next;
    				s.pop();
    			}
    			temp->next=nextnode;
    		}
    		else
    			break;
    		if(headflag==0){
    			head=begin;
    			headflag=1;
    		}
    		else
    			pre->next=begin;
    		pre=temp;
    		begin=nextnode;		
    	} 
    	return head;
        }

  • 0
    L

    Only constant memory is allowed.You use a stack, so I don't think the memory used in your code is constant.


  • 0
    S
    This post is deleted!

Log in to reply
 

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