Java code with explanation


  • 0
    L

    Basically the idea is try to remember the start position and end position.
    Reverse the nodes in between.

    For example as k =2,
    0(dummy)->1->2->3(end)->4-null
    start position will be 0, end will be 3, reverse 1->2
    so 0-> 2-> 1-> 3->4->null

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            
            ListNode str = dummy;
            ListNode cur = head;
            ListNode end = null;
            
            int i =0;
            while(head != null){
                i++;
                head= head.next;
                if (i % k ==0){
                    end = head;
                    ListNode pre = end;
                    
                    ListNode nstr = cur;
                    while(cur != end){
                        ListNode next = cur.next;
                        cur.next = pre;
                        pre = cur;
                        cur = next;
                    }
                    str.next = pre;
                    head = end;
                    //i = 0;
                    str = nstr;
                    cur = end;
                }
    
            }
            return dummy.next;
        }
    }
    

Log in to reply
 

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