Python Program to Reverse First N Elements of a Linked List

A linked list is a linear data structure used in computer science to store and manage collections of elements. In this Python program, we tackle the problem of reversing the order of the first N elements in a given linked list while leaving the rest of the list unchanged.

Problem Statement

Given a linked list and a positive integer N, reverse the order of the first N elements in the list, while keeping the remaining elements unchanged.

Python Program to Reverse First N Elements of a Linked List

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

class LinkedList:
    def __init__(self):
        self.head = None
    
    def append(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node
    
    def reverse_first_n(self, n):
        prev = None
        current = self.head
        for _ in range(n):
            if current:
                next_node = current.next
                current.next = prev
                prev = current
                current = next_node
        self.head = prev
    
    def display(self):
        current = self.head
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")

# Input: Creating a linked list
linked_list = LinkedList()
elements = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for element in elements:
    linked_list.append(element)

n = 4  # Number of elements to reverse

print("Original Linked List:")
linked_list.display()

linked_list.reverse_first_n(n)

print("\nLinked List after Reversing First", n, "Elements:")
linked_list.display()

Input / Output

Python Program to Reverse First N Elements of a Linked List

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...