Straightforward method to solve every group may help you


  • 0
    public ListNode reverseKGroup(ListNode head, int k) {
            if(head == null || k == 1)    return head;
            ListNode p = head;
            int count = 0;
            while(p != null) {
                count ++;
                p = p.next;
            }
            int groups = count / k;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode pre = dummy;
            for(int i = 0; i < groups; i ++) {
                ListNode cur = pre.next;
                ListNode next = cur.next;
                int n = 1;
                while(n < k) {
                    cur.next = next.next;
                    next.next = pre.next;
                    pre.next = next;
                    next = cur.next;
                    n ++;
                }
                pre = cur;
            }
            return dummy.next;
        }
    

Log in to reply
 

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