Search⌘ K

Solution Review: Move Tail to Head

Explore how to move the tail node to the head of a singly linked list using two pointers, understand pointer updates, and gain hands-on coding experience with Python implementations.

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 #

Python 3.5
def move_tail_to_head(self):
if self.head and self.head.next:
last = self.head
second_to_last = None
while last.next:
second_to_last = last
last = last.next
last.next = self.head
second_to_last.next = None
self.head = last

Explanation #

Let’s go over a line by line explanation of the solution above.

Line 2 ensures that the ...