Search code examples
pythonnodes

Rotating the Node chain to left n times and returning the new head of the Node chain not working as expected


I am to write a function called rotate(head, n) that takes the head of a Node chain and an integer, n, as parameters. The function must rotate the Node chain to the left n times and return the new head of the Node chain.

For example, given the following Node chain: A -> B -> C -> None

Rotating left one time would produce: B -> C -> A -> None I am to keep in mind that the node chain will contain at least three elements and n can be any non-negative integer.

Here is my Node class:

class Node:
    def __init__(self, data, next_node=None):
        self.__data = data
        self.__next = next_node

    def get_data(self):
        return self.__data

    def set_data(self, data):
        self.__data = data

    def get_next(self):
        return self.__next

    def set_next(self, new_next):
        self.__next = new_next
    
    def __str__(self):
        return f'{self.__data} -> {self.__next}'

This is my rotate() function:

def rotate(head, n):
    if (n == 0):
        return
    current = head
    while (current.get_next() != None):
        current = current.get_next()
   
    current.next = head
    current = head
    for i in range(n - 1):
        current = current.get_next()
   
    head = current.get_next()
    current = None
    return head

Test:

chain = from_list(['A', 'B', 'C'])
print(chain)
chain = rotate(chain, 1)
print(chain)

Expected Ouput:

A -> B -> C -> None
B -> C -> A -> None

Received Ouput:

A -> B -> C -> None
B -> C -> None

Test2:

chain = from_list(['A', 'B', 'C'])
print(chain)
chain = rotate(chain, 2)
print(chain)

Expected Output2:

A -> B -> C -> None
C -> A -> B -> None

Gotten Ouput2:

C -> A -> B -> None
A -> B -> C -> None
C -> None

TEST:

chain = from_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(chain)
chain = rotate(chain, 0)
print(chain)

EXPECT:

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None

GOT:

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None
None

Solution

  • You've got three small bugs, here's the correct version:

    def rotate(head, n):
        if (n == 0):
            return head # fixed
        current = head
        while (current.get_next() != None):
            current = current.get_next()
    
        current.set_next(head) # fixed
        current = head
        for i in range(n - 1):
            current = current.get_next()
       
        head = current.get_next()
        current.set_next(None) # fixed
        return head