Reversing a linked list is a common coding problem that tests your understanding of data structures and algorithmic thinking. It’s a foundational concept frequently asked in technical interviews, and mastering it helps you understand linked lists more deeply.

In this blog, we’ll discuss the problem in detail, explore different approaches to solving it, and provide implementations in multiple programming languages.


What Is a Linked List?

image 19
2 Elegant Approaches to Reverse a Linked List

A linked list is a linear data structure where elements, called nodes, are connected by pointers. Each node contains:

  • Data: The actual value of the node.
  • Next: A pointer to the next node in the sequence.

There are two main types of linked lists:

  1. Singly Linked List: Each node points to the next node, and the last node points to null.
  2. Doubly Linked List: Each node has two pointers: one to the next node and another to the previous node.

What Does Reversing a Linked List Mean?

Reversing a linked list means altering the direction of the pointers such that the first node becomes the last, and the last node becomes the first. For a singly linked list, this involves:

  • Changing the next pointer of each node to point to the previous node.
  • Updating the head of the list to point to the new first node.

Why Reverse a Linked List?

Reversing a linked list is not only a useful operation in various applications but also a problem-solving exercise that demonstrates:

  • Your ability to manipulate pointers.
  • Your understanding of iterative and recursive approaches.

Reversing a Linked List: Iterative Approach

The iterative approach is straightforward and efficient. The idea is to traverse the linked list and reverse the direction of the next pointer at each step.

Algorithm Steps

  1. Initialize three pointers:
  • prev as null.
  • current as the head of the list.
  • next as null.
  1. Traverse the list:
  • Store the next node (next = current.next).
  • Reverse the pointer (current.next = prev).
  • Move prev and current one step forward.
  1. Update the head to point to prev.

Python Code

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

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

# Example usage:
def print_list(head):
    while head:
        print(head.data, end=" -> ")
        head = head.next
    print("None")

# Create a linked list: 1 -> 2 -> 3 -> 4 -> None
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)

print("Original Linked List:")
print_list(head)

head = reverse_linked_list(head)

print("Reversed Linked List:")
print_list(head)

Output:

Original Linked List:
1 -> 2 -> 3 -> 4 -> None
Reversed Linked List:
4 -> 3 -> 2 -> 1 -> None

Reversing a Linked List: Recursive Approach

The recursive approach is elegant but slightly more challenging to understand. The idea is to reverse the smaller sublist first and then fix the current node.

image 20
Reversing a Linked List

Algorithm Steps

  1. Base case: If the list is empty or has only one node, return the node.
  2. Recursive step: Reverse the rest of the list.
  3. Fix the pointers:
  • head.next.next = head
  • head.next = None

Python Code

def reverse_linked_list_recursive(head):
    if not head or not head.next:
        return head
    new_head = reverse_linked_list_recursive(head.next)
    head.next.next = head
    head.next = None
    return new_head

# Example usage is the same as above

Time and Space Complexity

ApproachTime ComplexitySpace Complexity
Iterative(O(n))(O(1))
Recursive(O(n))(O(n)) (due to recursion stack)

Reversing a Doubly Linked List

For a doubly linked list, the process is slightly different because each node has two pointers: next and prev.

Algorithm Steps

  1. Traverse the list.
  2. Swap the next and prev pointers for each node.
  3. Update the head to the last node.

Python Code

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

def reverse_doubly_linked_list(head):
    current = head
    temp = None
    while current:
        temp = current.prev
        current.prev = current.next
        current.next = temp
        current = current.prev
    return temp.prev if temp else None

Practical Applications

  1. Data Reorganization: Reversing data for specific tasks, such as reversing a stack implemented with a linked list.
  2. Palindrome Check: Checking if a linked list is a palindrome.
  3. Custom Traversal: Iterating over a linked list in reverse order without using additional memory.

Conclusion

Reversing a linked list is a fundamental problem that highlights your understanding of pointers, recursion, and iterative approaches. By mastering this concept, you’ll be well-prepared for technical interviews and problem-solving challenges. Whether it’s a singly or doubly linked list, the approaches discussed in this blog will help you handle them efficiently.

10 FAQs related to reversing a linked list:


1. Can a linked list be reversed in place?

Yes, a linked list can be reversed in place using the iterative approach. This method alters the next pointers of the nodes without requiring additional memory.


2. What is the time complexity of reversing a linked list?

The time complexity for both iterative and recursive approaches is (O(n)), where (n) is the number of nodes in the linked list.


3. What is the space complexity of reversing a linked list?

  • Iterative approach: (O(1)) (no extra space required).
  • Recursive approach: (O(n)) due to the recursion stack.

4. Can a circular linked list be reversed?

Yes, a circular linked list can be reversed using a similar approach to a singly linked list. Special care must be taken to update the next pointer of the last node to point back to the head.


5. How do you reverse a doubly linked list?

To reverse a doubly linked list, traverse the list and swap the next and prev pointers for each node. Update the head to the last node.


6. Is the recursive approach better than the iterative approach?

The recursive approach is elegant but can cause a stack overflow for large linked lists due to its (O(n)) space complexity. The iterative approach is more memory-efficient.


7. Can I reverse only a portion of a linked list?

Yes, you can reverse a portion of a linked list by identifying the start and end of the sublist and reversing only the nodes in that range.


8. What happens if the linked list is empty?

If the linked list is empty (i.e., the head is null), the reverse function simply returns null.


9. Can I reverse a linked list in languages without explicit pointers, like Python?

Yes, reversing a linked list in languages like Python is straightforward as long as the linked list is implemented using node objects and their references.


10. How is reversing a linked list different from reversing an array?

  • Linked List: Reversing involves altering the pointers of nodes.
  • Array: Reversing swaps elements in place, making it simpler and faster in terms of memory access.

Reverse a Linked List on GeeksforGeeks

Reversing Linked Lists: Iterative and Recursive on Programiz

Reverse Linked List Problem on LeetCode

Linked List Basics and Reversal on Tutorials

PointVisualizing Linked List Reversal on VisualAlgo

Related Links –

A Deep Dive into Counting Sort: 7 Critical Factors for Success – https://kamleshsingad.com/wp-admin/post.php?post=5435&action=edit

How to Work with Virtual Environments in Python – https://kamleshsingad.com/wp-admin/post.php?post=5348&action=edit

15 Facts About Rotated Sorted Arrays You Should Know – https://kamleshsingad.com/wp-admin/post.php?post=5423&action=edit

LEAVE A REPLY

Please enter your comment!
Please enter your name here