Program to reverse inner nodes of a linked list in python

Given a linked list and two positions i and j, we need to reverse the nodes from position i to position j (0-indexed). The rest of the nodes remain in their original positions.

For example, if we have a linked list [1,2,3,4,5,6,7,8,9] with i = 2 and j = 6, the output will be [1, 2, 7, 6, 5, 4, 3, 8, 9].

Algorithm

To solve this problem, we follow these steps:

  • Create a dummy head node pointing to the original head
  • Traverse to find the node just before position i
  • Reverse the sublist from position i to position j
  • Reconnect the reversed sublist with the rest of the list

Implementation

class ListNode:
    def __init__(self, data, next_node=None):
        self.val = data
        self.next = next_node

def make_list(elements):
    """Helper function to create a linked list from a list of elements"""
    head = ListNode(elements[0])
    for element in elements[1:]:
        ptr = head
        while ptr.next:
            ptr = ptr.next
        ptr.next = ListNode(element)
    return head

def print_list(head):
    """Helper function to print the linked list"""
    ptr = head
    result = []
    while ptr:
        result.append(str(ptr.val))
        ptr = ptr.next
    print("[" + ", ".join(result) + "]")

class Solution:
    def solve(self, node, i, j):
        # Create dummy head to simplify edge cases
        prev_head = ListNode(None, node)
        prev, curr = prev_head, node

        # Move to position i
        for _ in range(i):
            prev, curr = curr, curr.next
        
        # Store references for reconnection
        rev_before, rev_end = prev, curr

        # Reverse the sublist from i to j
        for _ in range(j - i + 1):
            temp = curr.next
            curr.next = prev
            prev, curr = curr, temp

        # Reconnect the reversed sublist
        rev_before.next, rev_end.next = prev, curr

        return prev_head.next

# Test the solution
ob = Solution()
head = make_list([1, 2, 3, 4, 5, 6, 7, 8, 9])
i = 2
j = 6

print("Original list:")
print_list(head)

# Create the list again since we modified it
head = make_list([1, 2, 3, 4, 5, 6, 7, 8, 9])
result = ob.solve(head, i, j)

print(f"After reversing from position {i} to {j}:")
print_list(result)
Original list:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
After reversing from position 2 to 6:
[1, 2, 7, 6, 5, 4, 3, 8, 9]

How It Works

The algorithm works by using three pointers:

  • prev_head: A dummy node that points to the original head
  • rev_before: The node just before the reversal section
  • rev_end: The first node of the reversal section (which becomes the last after reversal)

We first navigate to position i, then reverse the sublist by changing the next pointers of nodes from position i to j. Finally, we reconnect the reversed portion with the rest of the list.

Time and Space Complexity

  • Time Complexity: O(n), where n is the number of nodes in the linked list
  • Space Complexity: O(1), as we only use a constant amount of extra space

Conclusion

This solution efficiently reverses a sublist within a linked list by using pointer manipulation. The key insight is to maintain references to the nodes that need reconnection after the reversal operation.

Updated on: 2026-03-25T12:49:18+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements