Simple, short coded, recursive solution in java


  • 0
    Z

    public class Solution{

    public ListNode reverseKGroup(ListNode head, int k) {
      if(k == 1 || head == null)  return head;
        ListNode node = head;
        int index = 0;
        while(index<k && node != null) {
            node = node.next;
            index++;
        }
        if(index!=k) return head;
    	node = reverseKGroup(node, k);
            ListNode prev = head;
            ListNode cur = head.next;
    	head.next = node;
            ListNode pointer = null;
            for(int i = 1;i<index;i++){
        	  pointer = cur.next;		
        	  cur.next = prev;
        	  prev = cur;
        	  cur = pointer;
    	}
        return prev;
    }}

Log in to reply
 

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