How to Reverse a Linked List in Python

Published:5 min read

How to Reverse a Linked List

Reversing a linked list in Python is one of the most common and fundamental problems in data structures. A linked list is a dynamic data structure where each node contains a value and a pointer to the next node. Reversing a linked list means changing the direction of these pointers so that the list flows in the opposite order. This problem is crucial for mastering linked list operations in Python, understanding pointers, and preparing for technical interviews. In this guide, you’ll learn step-by-step how to reverse a linked list using Python.

Steps to Solve How to Reverse a Linked List

  • Understand the Linked List Structure:
    • A linked list consists of nodes where each node contains:
      • A value (data).
      • A pointer to the next node.
  • Identify the Goal:
    • Reverse the linked list by changing the direction of the pointers so that the last node becomes the head.
  • Initialize Pointers:
    • Use three pointers:
      • prev to track the previous node (initially set to None).
      • current to track the current node (initially set to the head).
      • next to temporarily store the next node while reversing the pointer.
  • Iterate Through the Linked List:
    • For each node:
      • Save the next node using the next pointer.
      • Reverse the current.next pointer to point to the prev node.
      • Move prev to current and current to next.
  • Update the Head:
    • After the loop, prev will point to the new head of the reversed linked list. Update the head to prev.
  • Handle Edge Cases:
    • For an empty linked list, return None.
    • If the linked list has only one node, it is already reversed.
  • Test the Solution:
    • Example:
      • Input: 1 -> 2 -> 3 -> 4 -> 5
      • Output: 5 -> 4 -> 3 -> 2 -> 1
  • Optimize Space Usage:
    • This solution operates in O(1) space and O(n) time complexity, making it efficient for large linked lists.
Reverse a Linked List

Did you know you can easily reverse a linked list?

Imagine a line of people holding hands, and you need to reverse their positions without breaking the chain. Reversing a linked list is somewhat similar. It might sound complex, but with the right approach, it becomes really straight forward. Let's dive into how to reverse a linked list using Python.

What is a linked list?

A linked list is quite similar to other data structures, but all its elements are not kept in contiguous memory locations. The elements in a linked list are linked with each other using pointers.

Reversing a Linked List

In this section, we will learn how to reverse a linked list and at the same time practice the first way told in the introduction, i.e., reversing each link.

Step 1: Define the Nodes Structure

let's first define the structure of a node. Each node will have a data part and a reference to the next node.

python
1
2
3
4
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val  # Store the data in the node
        self.next = next  # Initialize the next pointer to None

Step 2: Create the linked list

Now, let’s create the linked list and add methods to append nodes and reverse the list.

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class LinkedList:
    def __init__(self):
        self.head = None  # Initialize the head of the list to None

    # Function to add a new node at the end
    def append(self, data):
        new_node = ListNode(data)
        if not self.head:
            self.head = new_node  # If the list is empty, make the new node the head
            return
        last = self.head
        while last.next:
            last = last.next  # Traverse to the end of the list
        last.next = new_node  # Link the new node at the end of the list

    # Function to reverse the linked list
    def reverse(self):
        prev = None
        current = self.head
        while current:
            next_node = current.next  # Store the next node
            current.next = prev  # Reverse the current node's pointer
            prev = current  # Move pointers one position ahead
            current = next_node
        self.head = prev  # Update the head to the new first node

    # Function to print the linked list
    def printList(self):
        current = self.head
        while current:
            print(current.val, end=" -> ")
            current = current.next
        print("NULL")

Step 3: Example usage

Here’s how you can use the above functions to create a linked list, add nodes, and reverse the list.

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if __name__ == "__main__":
    llist = LinkedList()
    llist.append(1)
    llist.append(2)
    llist.append(3)
    llist.append(4)
    llist.append(5)

    print("Original List:")
    llist.printList()

    llist.reverse()

    print("Reversed List:")
    llist.printList()

Explanation of code

  • Class Definition: We start by defining a ListNode class to represent each node in the linked list.
  • Linked List Implementation: The LinkedList class manages the nodes. It includes methods to append new nodes, reverse the list, and print the list.
  • Appending Nodes: The append method adds new nodes to the end of the list.
  • Reversing the List: The reverse method iteratively reverses the pointers of the nodes.
  • Printing the List: The printList method prints the linked list.

Key points to remember

  • Pointer Manipulation: Understanding how to change pointers is crucial.
  • Iterative Approach: This method uses an iterative approach to reverse the list.
  • Memory Management: Ensure that all nodes are correctly pointed to avoid memory leaks or broken links.

Conclusion

Reversing a linked list in Python is hence very critical for coding interviews. This will surely give you the ability to handle linked lists and reinforce your data structure knowledge. Keep in practice, and soon you'll handle your linked list in your projects like a pro!

Frequently Asked Questions

Yes, you can reverse a linked list. Reversing a linked list involves changing the direction of the pointers so that the last node becomes the first node and the first node becomes the last. This operation can be performed iteratively or recursively by adjusting the next pointers of the nodes in the list.

The in-place reversal of a linked list pattern involves reversing the linked list without using any extra space for another list. This is typically done by iterating through the list and changing the next pointer of each node to point to the previous node instead of the next one. The algorithm maintains three pointers: prev, curr, and next, where prev starts as null, curr starts as the head, and next is used to temporarily store the next node before updating pointers.

The naive approach to reversing a linked list involves using additional space, such as an array or another linked list. First, you traverse the original list and store the values in an array or push them onto a stack. Then, you recreate the linked list in reverse order by either popping from the stack or reading the array from the end to the beginning. This approach, while simple, is not efficient in terms of space complexity.

To reverse the second half of a linked list, you first need to find the middle of the list. You can do this using the slow and fast pointer technique, where the slow pointer moves one step at a time, and the fast pointer moves two steps. Once the fast pointer reaches the end, the slow pointer will be at the middle of the list. Then, you reverse the portion of the list starting from the middle node onward using the standard reversal technique (iteratively or recursively). After reversing, you can connect the first half with the newly reversed second half.

Still have questions?Contact our support team

Related Articles

Sign-in First to Add Comment

Leave a comment 💬

All Comments

No comments yet.