Simple iterative Java code with comment


  • 0
    N

    Idea is simple: count the size of the linked list, then use for loop to control how many times we need to reverse group of k. then call another function to do the same thing as "reverse linked list II"

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null || k == 1) {
            return head;
        }
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        int size = 0;
        ListNode cur = head;
        while (cur != null) {
            size++;
            cur = cur.next;
        }
        
        ListNode pre = dummy;
        for (int i = 1; i + k - 1 <= size; i += k) {
            pre = reverseBetween(pre, k);
        }
        
        return dummy.next;
    }
    
    public ListNode reverseBetween(ListNode node, int k) {
        ListNode start = node.next;
        ListNode then = start.next;
        System.out.println(node.val);
        for (int i = 1; i < k; ++i) {
            start.next = then.next;
            then.next = node.next;
            node.next = then;
            then = start.next;
        }
        return start;
    }

Log in to reply
 

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