Java non-recursive solution with constant space


  • 0
    N
    
    
    
    public class Solution {
    
        public ListNode reverseKGroup(ListNode head, int k) {
    
            ListNode pre = new ListNode(0);
            ListNode dummy = pre;
            ListNode cur = head;
            ListNode [] pts = new ListNode[k];
            while(cur!=null){
                int i = 0;
            	for(i=0;i<k;i++){
            		ListNode tmp = cur;
            		pts[i] = tmp;
            		cur = cur.next;
            		if(cur == null){
            			break;
            		}
            		
            	}
            	//finished one group of k nodes
            	if(i<k-1){
            		//just append
            		for(int j=0;j<=i;j++){
            			pre.next = pts[j];
            			pre = pre.next;
            		}
            	}
            	else{
            	//need to swap
            		for(int j=k-1;j>=0;j--){
            			pre.next = pts[j];
            			pre = pre.next;
            		}
            	}
            	
            }
        	pre.next = null;
    		return dummy.next;
        }
    }
    
    

Log in to reply
 

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