Accenture | OA | Move k nodes starting from index n to front of Linked List
Anonymous User
421

Problem: Given a Linked List head, move k nodes starting from index n to the front of given LL.

 Input: head = [1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 ] , n = 3 , k = 4
 output: 4 -> 5 -> 6 -> 7 -> 1 -> 2 -> 3 -> 8 -> 9

Java Code

public static ListNode moveKNodesStartingFromNToFront(ListNode head, int n, int k) {
       // Input: head = [1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 ] , n = 3 , k = 4
       // output: 4 -> 5 -> 6 -> 7 -> 1 -> 2 -> 3 -> 8 -> 9

        ListNode dummy = head;
        ListNode dummy2 = dummy; // 1->2->3

        int countN = 1;
        while (countN < n) {
            countN++;
            dummy = dummy.next;
        }

        head = dummy.next;
        ListNode firstHead = head; // 4 -> 5 -> 6 -> 7
        dummy.next = null; // separate the first part

        int countK = 1;
        while (countK < k) {
            firstHead = firstHead.next;
            countK++;
        }

        ListNode lastHead = firstHead.next;
        firstHead.next = dummy2; // this gives 4567... 123

        while (firstHead.next != null){
            firstHead = firstHead.next;
        }

        firstHead.next =lastHead;
        return head;
    }
Comments (2)