Straightforward implement


  • 0
    V

    public class No025_Reverse_Nodes_in_kGroup {
    public ListNode reverseKGroup(ListNode head, int k) {

        if (head == null || k <= 1) return head;
    
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev = dummy;
        ListNode dummy2 = new ListNode(0);
        ListNode tail = null;
    
        int i = 0;
        while (head != null) {
            i = 0;
            while (head != null && i < k) {
                if (dummy2.next == null) {
                    dummy2.next = head;
    
                    tail = head;
                    head = head.next;
                    tail.next = null;
                } else {
                    ListNode tmp = head.next;
                    head.next = dummy2.next;
                    dummy2.next = head;
                    head = tmp;
                }
                i++;
            }
            if (i == k) {
                //perfect match
                prev.next = dummy2.next;
                prev = tail;
                dummy2.next = null;
    
            }
    
        }
        if (i > 0 && i < k) {
            prev.next = null;
            //left-out node deals
            while (dummy2.next != null) {
                ListNode tmpNode = dummy2.next.next;
                dummy2.next.next = prev.next;
                prev.next = dummy2.next;
                dummy2.next = tmpNode;
    
            }
        }
        return dummy.next;
    }
    

    }


Log in to reply
 

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