Python Program to Reverse only First N Elements of a Linked List

When it is required to reverse a specific set of elements in a linked list, a method named 'reverse_list' is defined. This iterates through the list and reverses the first N elements while keeping the remaining elements unchanged.

Below is a demonstration for the same −

Example

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

class LinkedList_structure:
    def __init__(self):
        self.head = None
        self.last_node = None

    def add_vals(self, data):
        if self.last_node is None:
            self.head = Node(data)
            self.last_node = self.head
        else:
            self.last_node.next = Node(data)
            self.last_node = self.last_node.next

    def print_it(self):
        curr = self.head
        while curr:
            print(curr.data, end=" ")
            curr = curr.next
        print()

def reverse_list(my_list, n):
    if n == 0:
        return
    before_val = None
    curr = my_list.head
    if curr is None:
        return
    after_val = curr.next
    
    for i in range(n):
        curr.next = before_val
        before_val = curr
        curr = after_val
        if after_val is None:
            break
        after_val = after_val.next
    
    my_list.head.next = curr
    my_list.head = before_val

# Create linked list instance
my_instance = LinkedList_structure()

# Add elements to the linked list
elements = [45, 67, 89, 12, 345]
for elem in elements:
    my_instance.add_vals(elem)

print("Original linked list:")
my_instance.print_it()

n = 3
print(f"Reversing first {n} elements...")

reverse_list(my_instance, n)

print("The new list is:")
my_instance.print_it()

Output

Original linked list:
45 67 89 12 345 

Reversing first 3 elements...
The new list is:
89 67 45 12 345 

How It Works

The algorithm works by using three pointers to reverse the first N elements:

  • before_val: Points to the previous node in the reversed section

  • curr: Points to the current node being processed

  • after_val: Points to the next node to maintain the chain

For each of the first N nodes, the algorithm reverses the pointer direction and moves to the next node. After reversing N elements, it connects the reversed section back to the remaining unchanged part of the list.

Interactive Example

# Interactive version with user input
my_instance = LinkedList_structure()
my_list = input('Enter the elements of the linked list... ').split()
for elem in my_list:
    my_instance.add_vals(int(elem))

n = int(input('Enter the number of elements you wish to reverse in the list... '))

reverse_list(my_instance, n)

print('The new list is:')
my_instance.print_it()

Key Points

  • The Node class represents individual elements in the linked list

  • The LinkedList_structure class manages the linked list operations

  • The reverse_list function reverses only the first N elements

  • Time complexity is O(n) and space complexity is O(1)

Conclusion

Reversing the first N elements of a linked list is efficiently achieved using pointer manipulation. The algorithm maintains the original structure while reversing only the specified portion, making it useful for partial list reorganization.

Updated on: 2026-03-25T18:39:20+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements