📜  门| GATE 2017 MOCK II |第 39 题(1)

📅  最后修改于: 2023-12-03 15:28:36.299000             🧑  作者: Mango

GATE 2017 MOCK II - Question 39

Problem Statement

You are given a linked list of size $n$. The list is indexed from $0$ through $n-1$. You are also given an integer, $k$, such that $0 \leq k < n$. You need to rotate the linked list by $k$ positions to the right.

Example

Let's consider the following linked list with $n=5$ nodes:

0 -> 1 -> 2 -> 3 -> 4 -> null

If $k=2$, the list should be rotated to the right by 2 positions and become:

3 -> 4 -> 0 -> 1 -> 2 -> null
Approach

The easiest way to solve this problem is to make use of the two-pointer approach which involves 'k' and 'last' pointers. Initially, both pointers will point to the first node of the linked list. The 'last' pointer will then be moved 'k' nodes ahead of the 'k' pointer. This means that the 'k' pointer will still remain at the first node, while the 'last' will jump 'k' nodes to reach the $k^{th}$ node.

Now, we will start moving both the pointers one by one, until the 'last' pointer reaches the last node of the linked list. This will ensure that the 'k' pointer is now pointing to the $(n-k)^{th}$ node of the linked list. At this point, we will simply swap the 'k' pointer with the head of the linked list, to get the final rotated list.

Code

Here is a sample implementation of the approach described above, in Python.

def rotate_right(head, k):
    # Edge case when linked list is empty
    if head is None:
        return None

    # Counting the number of nodes
    count = 1
    current_node = head
    while current_node.next is not None:
        current_node = current_node.next
        count += 1

    # Adjusting the value of k
    k = k % count

    # Edge case when k has zero value
    if k == 0:
        return head

    # Creating the first pointer
    first_pointer = head

    # Creating the second pointer
    second_pointer = head

    # Moving the second pointer by k positions
    for i in range(k):
        second_pointer = second_pointer.next

    # Moving the first and second pointers by one position,
    # until second pointer reaches the end of the list
    while second_pointer.next is not None:
        first_pointer = first_pointer.next
        second_pointer = second_pointer.next

    # Swapping the pointers to get the rotated list
    new_head = first_pointer.next
    first_pointer.next = None
    second_pointer.next = head

    return new_head

This implementation takes the head of the linked list as the input along with the value of 'k'. It returns the head of the rotated list.