This is a Python program to read a linked list in reverse.
The program creates a singly linked list and allows the user to enter data items to the list in reverse.
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variable head.
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.
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 class LinkedList: def __init__(self): self.head = None def insert_at_beg(self, new_node): if self.head is None: self.head = new_node else: new_node.next = self.head self.head = new_node def display(self): current = self.head while current: print(current.data, end = ' ') current = current.next a_llist = LinkedList() 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()
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.
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 The linked list: 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.
- Get Free Certificate of Merit in Python Programming
- Participate in Python Programming Certification Contest
- Become a Top Ranker in Python Programming
- Take Python Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Apply for Programming Internship
- Practice Programming MCQs
- Apply for Python Internship
- Buy Information Technology Books
- Buy Python Books