Reverse Nodes in k-Group(0025/Hard)

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.

For 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

costs O(n) time, O(1) space.

public ListNode reverseKGroup(ListNode head, int k) {
    ListNode dummy = new ListNode(0);
    ListNode  prev = dummy, p1 = head, p2 = head;

    while(p2 != null){
        int i = 0;
        for (; i < k && p2 != null; i++)
            p2 = p2.next;

        //count smaller than k, don't need reverse
        if (i < k){
            prev.next = p1;
            break;
        }

    //reverse from p1 to the node before p2, and Let t record the tail (lastNode) of the reverse slot
        ListNode t = null;
        while (p1 != p2){
            ListNode p1n = p1.next;
            p1.next = prev.next;
            prev.next = p1;
            if (t == null)
                t = p1;

            p1 = p1n;
        }

        prev = t;
    }
    return dummy.next;
}

results matching ""

    No results matching ""