Java solution with reverse approach


  • 0
    C
    public ListNode reverseKGroup(ListNode head, int k) {
            if(head == null || k <= 1) return head;
            int cnt = 0;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode prev = dummy;
            while(head != null) {
                if(++cnt%k == 0) {
                	ListNode next = prev.next;
                    prev.next = reverse(prev.next, head.next, head.next);
                    prev = next;
                    head = next.next;
                }
                else head = head.next;
            }
            return dummy.next;
        }
        private ListNode reverse(ListNode begin, ListNode end, ListNode tail) {
            ListNode first = null;
            ListNode last = begin;
            while(begin != end) {
                ListNode oldFirst = first;
                first = begin;
                begin = begin.next;
                first.next = oldFirst;
            }
            last.next = tail;
            return first;
        }

Log in to reply
 

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