My java solution


  • 0
    H
    public class Solution {
    
    public class ListNode {
    	int val;
    	ListNode next;
    
    	ListNode(int x) {
    		val = x;
    		next = null;
    	}
    }
    
    public ListNode reverseKGroup(ListNode head, int k) {
    	if (head == null)
    		return null;
    	if (k == 1)
    		return head;
    	ListNode t = head;
    	int i = 0;
    	int tlen = 0;
    	ListNode lh = head;
    	ListNode th = head;
    	ListNode tr = head;
    	List<ListNode[]> lln = new ArrayList<ListNode[]>();
    
    	while (t != null) {
    		if (i == 0) {
    			th = t;
    			i++;
    			t = t.next;
    		} else if (i < k - 1) {
    			i++;
    			t = t.next;
    		} else if (i == k - 1) {
    			tr = t;
    			t = t.next;
    			tr.next = null;
    			i = 0;
    			ListNode[] o = { th, tr };
    			lln.add(o);
    			tlen++;
    		}
    	}
    	if (i == 0)
    		lh = null;
    	else
    		lh = th;
    
    	int j = 0;
    	ListNode rh = null;
    	ListNode rt = null;
    	if (tlen == 0)
    		return lh;
    	while (j < tlen) {
    		ListNode rl[] = reverseList(lln.get(j)[0]);
    		if (j == 0) {
    			rh = rl[0];
    			rt = rl[1];
    		} else {
    			rt.next = rl[0];
    			rt = rl[1];
    		}
    		++j;
    	}
    	rt.next = lh;
    	return rh;
    
    }
    
    public ListNode[] reverseList(ListNode head) {
    	ListNode t = head;
    	ListNode th = head;
    	ListNode rail = head;
    	head = null;
    	while (t != null) {
    		th = t.next;
    		t.next = head;
    		head = t;
    		t = th;
    	}
    	ListNode result[] = { head, rail };
    	return result;
    }
    
    }

Log in to reply
 

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