Straightforward Iterative Java Solution


  • 0
    public ListNode reverseKGroup(ListNode head, int k) {
    	ListNode dummy = new ListNode(0), cur = dummy;
    	while (head != null) {
    		ListNode tail = head;
    		int count = k;
    		while (tail != null && count > 1) {
    			tail = tail.next;
    			count--;
    		}
    		// tail == null || count == 1
    		if (tail == null) {
    			cur.next = head;
    			break;
    		}
    		ListNode next = tail.next;
    		cur.next = reverse(head, tail);
    		cur = head;
    		head = next;
    	}
    	return dummy.next;
    }
    
    // iteratively reverse the partial linked list, starting from head, and
    // ending at tail
    private ListNode reverse(ListNode head, ListNode tail) {
    	ListNode left = head, right = tail.next, prev = null, next = null;
    	while (left != right) {
    		next = left.next;
    		left.next = prev;
    		prev = left;
    		left = next;
    	}
    	return tail;
    }

Log in to reply
 

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