Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.

Have you met this question in a real interview?

Yes

Example

Given this linked list:1->2->3->4->5

For k = 2, you should return:2->1->4->3->5

For k = 3, you should return:3->2->1->4->5

so we need to cut the list into several parts, and reverse them

  1. when reverse, for example, we want to reverse 1->2->3 then become 3->2->1, we need to connect the last node(after reverse) to the new head. in this case, 1 -> 4
  2. have to check if the remaining nodes >= k
public class Solution {
    /**
     * @param head a ListNode
     * @param k an integer
     * @return a ListNode
     */
    public ListNode reverseKGroup(ListNode head, int k) {
        // Write your code here
        if (head == null || k <= 1) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;

        while (head.next != null) {
            head = reverseK(head, k);
        }

        return dummy.next;
    }


    public ListNode reverseK(ListNode head, int k) {
        //validate if the remaining has enough
        head = hasEnough(head, k);
        if (head.next == null) {
            return head;
        }

        ListNode tail = head.next;
        ListNode prev = head;
        ListNode curt = head.next;
        for (int i = 0; i < k; i++) {
            ListNode temp = curt.next;
            curt.next = prev;
            prev = curt;
            curt = temp;
        }


        head.next = prev;
        tail.next = curt;
        return tail;
    }

    public ListNode hasEnough(ListNode head, int k) {
        ListNode next = head;
        for (int i = 0; i < k; i++) {
            if (next.next == null) {
                return next;
            }

            next = next.next;
        }
        return head;
    }
}

results matching ""

    No results matching ""