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

This is a Python program to reverse the first N elements of a linked list.

Problem Description

The program creates a linked list and reverses its first N elements.

Problem Solution

1. Create a class Node with instance variables data and next.
3. The variable head points to the first element in the linked list while last_node points to the last.
4. Define methods append and display.
5. The method append takes a data item as argument and appends a node with that data item to the list.
6. The method display traverses the list from the first node and prints the data of each node.
7. Define a function reverse_llist which takes a linked list as argument and a number n.
8. The function reverse_llist iterates through the list using three pointers to reverse the first n elements.
9. Create an instance of LinkedList, reverse the first n elements of the list and display it.

Program/Source Code

Here is the source code of a Python program to reverse the first N elements of a linked list. The program output is shown below.

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

def __init__(self):
self.last_node = None

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

def display(self):
while current:
print(current.data, end = ' ')
current = current.next

def reverse_llist(llist, n):
if n == 0:
return
before = None
if current is None:
return
after = current.next
for i in range(n):
current.next = before
before = current
current = after
if after is None:
break
after = after.next

for data in data_list:
a_llist.append(int(data))
n = int(input('Enter the number of elements you want to reverse in the list: '))

reverse_llist(a_llist, n)

print('The new list: ')
a_llist.display()```
Program Explanation

1. An instance of LinkedList is created.
2. The user is prompted to enter the data items for the list.
3. The user is asked for n, the number of elements they would like to reverse.
4. The function reverse_llist is called to reverse the first n elements.
5. The linked list is displayed.

Runtime Test Cases
```Case 1:
Please enter the elements in the linked list: 1 2 3 4 5 6 7
Enter the number of elements you want to reverse in the list: 4
The new list:
4 3 2 1 5 6 7

Case 2:
Enter the number of elements you want to reverse in the list: 1
The new list:
7 2 4

Case 3:
Enter the number of elements you want to reverse in the list: 3
The new list:
2 3 8```

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!