My Java Solution Using iteration


  • 0
    T
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode inputDummy = new ListNode(0);
        	inputDummy.next = head;
        	ListNode resDummy = new ListNode(0);
        	ListNode resPos = resDummy;
        	
        	while( inputDummy.next != null ){
        		//move
        		ListNode inputPos = inputDummy;
        		for( int count = 0; count < k; count++ ){
        			if( inputPos.next!= null )
        				inputPos = inputPos.next;
        			else {
        				resPos.next = inputDummy.next;
        				return resDummy.next;
        			}
        		}
        		//delete and insert
        		inputPos = inputDummy.next;
        		for( int i = 0; i < k; i++ ){
        			ListNode cur = inputDummy.next;
        			inputDummy.next = cur.next;
        			cur.next = resPos.next;
        			resPos.next = cur;
        		}
        		//move index of pointer
        		resPos = inputPos;
        	}
        	return resDummy.next;
        }
    

Log in to reply
 

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