1ms Java Solution


  • 0
    A
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode result = getKthNode(head, k);
            if (result == null) return head;
            ListNode last_tail = null, new_head = null, next_head = head;
            ListNode temp1 = head;
            while (true) {
                new_head = reverse(next_head, k);
                //System.out.println(new_head.val);
                if (new_head != null) {
                    if (last_tail != null) {
                        last_tail.next = new_head;
                    }
                    last_tail = next_head;
                    next_head = next_head.next;
                } else {
                    break;
                }
            }
            return result;
        }
        
        public ListNode reverse(ListNode head, int k) {
            if (isLengthAtLeastK(head, k) == false) {
                return null;
            }
            ListNode a = null, b = head, c = null;
            int cnt = 1;
            while (cnt <= k) {
                c = b.next;
                cnt++;
                b.next = a;
                a = b;
                b = c;
            }
            head.next = b;
            return a;
        }
        
        boolean isLengthAtLeastK(ListNode head, int k) {
            int cnt = 0;
            while (head != null && cnt < k) {
                cnt++;
                head = head.next;
            }
            return cnt == k;
        }
        
        ListNode getKthNode(ListNode head, int k) {
            ListNode temp = head;
            int cnt = 1;
            while (temp != null && cnt < k) {
                temp = temp.next;
                cnt++;
            }
            if (cnt == k) {
                return temp;
            } else {
                return null;
            }
        }
    }

Log in to reply
 

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