Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Solution Review: Move Tail to Head

Sumit Rawal answered on May 18, 2023 Popularity 1/10 Helpfulness 1/10

Contents


More Related Answers

  • Exercise: Move Tail to Head

  • Solution Review: Move Tail to Head

    0

    Line 2 ensures that the code proceeds to line 3 if there is more than one element in the linked list. This implies self.head and self.head.next is not None. We initialize last and second_to_last to self.head and None on lines 3-4. Now we have to make them point to what they are supposed to point to, i.e., last should point to the last node while second_to_last should point to the second to last node in a linked list. Therefore, we traverse the linked list using the while loop on line 5. The while loop will run until last.next becomes None which implies that last is the last node in the linked list. Before updating last to last.next on line 7, we keep updating second_to_last to last on line 6 so that in the last iteration, when last is the last node in the linked list, second_to_last will be the second to last node in the linked list.

    Now that the two pointers are rightly positioned, we have to change a few pointers to complete our solution. Therefore, last.next which was previously pointing to None is pointed to self.head on line 8. This makes a circular linked list where the last node points to the first element of the linked list. To make the linked list linear, we make second_to_last.next point to None on line 9. In this way, we have updated the tail pointer of the linked list. At this stage, all that is left is to update the head pointer which we do on line 10, and set self.head equal to last. This completes our solution when we have to move the tail node to the head. 

    Popularity 1/10 Helpfulness 1/10 Language whatever
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 18 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.