My non-recursive Java solution


  • 0
    Z
    /**
     * 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) {
            if(head==null || k ==0) return head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode Pre = dummy, post = dummy;
            while(true){
                for(int i = 1; i <=k; ++i){
                    post =  post.next;
                    if(post==null) break;
                }
                if(post==null) break;
                ListNode M = Pre.next;
                for(int i = 1; i <k; ++i){
                    ListNode curr = M.next;
                    M.next = curr.next;
                    curr.next = Pre.next;
                    Pre.next = curr;
                }
                Pre = M;
                post = M;
            }
            return dummy.next;
            
        }
    }

Log in to reply
 

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