Flipping the Script: Reversing a Linked List in Python for Interview Success

Christopher Franklin
Weekly Python
Published in
5 min readMay 15, 2023

Introduction

Reversing a linked list is a classic problem often encountered in technical interviews, testing a candidate's knowledge of data structures, particularly linked lists. This post aims to provide a comprehensive guide on how to reverse a linked list using Python, complete with code examples and explanations.

Understanding Linked Lists

A linked list is a linear data structure where each element is a separate object. Each element (node) of a list consists of two items - the data and a reference (link) to the next node. The last node has a reference to null, indicating the end of the list.

Here's a simple definition of a Node class in Python:

class Node:
def __init__(self, data=None):
self.data = data
self.next = None

Reversing a Linked List

Reversing a linked list essentially means reversing the direction of the 'next' pointer of every node in the list.

Here's a Python function that accomplishes this:

def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev

This function iterates over the linked list, at each step changing the 'next' pointer of the current node to point to the previous node. It uses a temporary variable 'next_node' to keep track of the original next node before overwriting the 'next' pointer.

Applications of Reversed Linked Lists in Interview Questions

Reversing a linked list can be a useful operation for a variety of interview problems. Here are a couple of examples:

Problem: Palindrome Linked List

Given a singly linked list, determine if it is a palindrome. An efficient solution can first reverse the second half of the linked list, and then compare it with the first half.

To solve the "Palindrome Linked List" problem, we can use a fast and slow pointer approach to get the middle of the linked list, then reverse the second half of the list. Finally, we compare the first half and the second half to determine if the linked list is a palindrome.

Here's the Python code:

class Node:
def __init__(self, data=None):
self.data = data
self.next = None

def is_palindrome(head):
# Step 1: Get the middle of the linked list
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next

# Step 2: Reverse the second half of the list
prev = None
while slow:
next_node = slow.next
slow.next = prev
prev = slow
slow = next_node

# Step 3: Compare the first and second half nodes
while prev: # Use prev as the head of the second half
if prev.data != head.data:
return False
prev = prev.next
head = head.next
return True

# Test case: a palindrome linked list "1->2->2->1"
node1 = Node(1)
node2 = Node(2)
node3 = Node(2)
node4 = Node(1)
node1.next = node2
node2.next = node3
node3.next = node4
print(is_palindrome(node1)) # Output: True

In this code, is_palindrome function is checking whether the linked list is a palindrome. It first finds the middle of the linked list using the fast and slow pointers technique. Then it reverses the second half of the linked list. Finally, it compares the first half and the reversed second half of the linked list. If they are identical, then the linked list is a palindrome.

Problem: Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. This problem can be solved by reversing k nodes at a time.

The "Reverse Nodes in k-Group" problem is a bit more complicated, as it involves reversing segments of a linked list. Here's how you could solve it using Python:

class Node:
def __init__(self, data=None):
self.data = data
self.next = None

def reverse_k_group(head, k):
if head is None or k < 2:
return head

next_head = head
for _ in range(k):
if next_head is None:
return head
next_head = next_head.next

prev, current = None, head
next_node = None
for _ in range(k):
next_node = current.next
current.next = prev
prev = current
current = next_node

if next_node is not None:
# still have some nodes left, reverse them in k groups
head.next = reverse_k_group(next_node, k)

return prev

# Helper function to print the linked list
def print_list(node):
while node is not None:
print(node.data, end=" ")
node = node.next
print()

# Test case: a linked list "1->2->3->4->5" and k = 3
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
print_list(node1) # Output: 1 2 3 4 5
result = reverse_k_group(node1, 3)
print_list(result) # Output: 3 2 1 4 5

This Python script first defines a Node class to represent a node in a linked list. The reverse_k_group function then reverses every k nodes in the linked list. If there are less than k nodes left, it doesn't reverse them. The print_list function is used to print the linked list for testing purposes.

Tips for Linked List Problems

Understand the properties

Linked lists have unique properties that differentiate them from other data structures. Understanding these properties, such as how nodes reference each other, is crucial for solving linked list problems.

Use multiple pointers

Often, you'll need to keep track of multiple positions in the linked list at once. Don't hesitate to use multiple pointers to accomplish this.

Be careful with edge cases

Edge cases, particularly dealing with the head and tail of the list, can be tricky. Make sure to handle these cases correctly.

Conclusion

Mastering the reversal of a linked list can be a significant step towards success in coding interviews. This operation not only tests your understanding of linked lists as a data structure, but also your ability to manipulate pointers and handle edge cases. As with any concept, the key to becoming comfortable with reversing a linked list is practice. So, keep practicing, and happy coding!

P.S. Want weekly python coding challenges and news? Sign up for the newsletter to get them directly in your inbox: https://weeklypython.substack.com/welcome

--

--