This is a Python program to read a linked list in reverse.

Problem Description

The program creates a singly linked list and allows the user to enter data items to the list in reverse.

Problem Solution

1. Create a class Node with instance variables data and next.
3. The variable head points to the first element in the singly linked list.
4. Define methods insert_at_beg and display.
5. The method insert_at_beg inserts a node at the first position of the list.
6. The method display traverses the list from the first node and prints the data of each node.
7. Create an instance of LinkedList and prepend the data items input by the user.

Program/Source Code

Here is the source code of a Python program to read a linked list in reverse. The program output is shown below.

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

def __init__(self):

def insert_at_beg(self, new_node):
else:

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

n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
node = Node(data)
a_llist.insert_at_beg(node)

print('The linked list: ', end = '')
a_llist.display()
Program Explanation

1. An instance of LinkedList is created.
2. The user is prompted to provide data items for the list.
3. The insert_at_beg method is used to enter the data to the list in reverse.

Runtime Test Cases
Case 1:
How many elements would you like to add? 4
Enter data item: 5
Enter data item: 3
Enter data item: 10
Enter data item: 2
The linked list: 2 10 3 5

Case 2:
How many elements would you like to add? 1
Enter data item: 8

Case 3:
How many elements would you like to add? 3
Enter data item: 1
Enter data item: 2
Enter data item: 3
The linked list: 3 2 1

Sanfoundry Global Education & Learning Series – Python Programs.

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

Note: Join free Sanfoundry classes at Telegram or Youtube