Solution Review: Move Tail to Head
This lesson contains the solution review for the challenge of moving the tail node of a linked list to the head.
We'll cover the following...
For this problem, we will use two pointers where one will keep track of the last node of the linked list, and the other will point to the second-to-last node of the linked list. Let’s have a look at the code below.
Implementation #
Press + to interact
def move_tail_to_head(self):if self.head and self.head.next:last = self.headsecond_to_last = Nonewhile last.next:second_to_last = lastlast = last.nextlast.next = self.headsecond_to_last.next = Noneself.head = last
Explanation #
Let’s go over a line by line explanation of the solution above.
Line 2 ensures that the ...