2passes stupid solution


  • 0
    I

    this one has same pattern as 92. Reverse Linked List II

    public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null) return null;
            ListNode dummy = new ListNode(0);
            ListNode pre = dummy;
            pre.next = head;
            
            ListNode start = head;
            ListNode then = start.next;
            
            // find the size
            int counter = 0;
            ListNode cur = head;
            while (cur != null){
                cur = cur.next;
                counter++;
            }
            
            while (counter / k > 0){
                // 1 2 3 4 5
                // k = 2, counter = 5
                // 2 1 3 4 5
                for (int i=1; i<k&&start!=null&&then!=null; i++){
                    start.next = then.next;
                    then.next = pre.next;
                    pre.next = then;
                    then = start.next;
                }
                // start a new round, reset 
                pre = start;
                start = then;
                if (start != null){
                    then = start.next;
                }
                counter = counter - k;
            }
            
            return dummy.next;
        }
    

Log in to reply
 

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