How to Create Reverse a Linked List in Python
In this tutorial, we will program "How to Reverse a Linked List in Python". We will learn how to identify and reverse a linked list. The objective is to safely and accurately reverse the given linked list. I will provide a sample program to demonstrate the coding process.
This topic is very easy to understand. Just follow the instructions I provide, and you'll be able to do it yourself with ease. The program I’ll show you demonstrates the proper way to reverse a linked list. I’ll also provide a simple and efficient method to achieve this. So, let's start coding!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- class Node:
- def __init__(self, data):
- self.data = data
- self.next = None
- class LinkedList:
- def __init__(self):
- self.head = None
- def reverseUtil(self, curr, prev):
- if curr.next is None:
- self.head = curr
- curr.next = prev
- return
- next = curr.next
- curr.next = prev
- self.reverseUtil(next, curr)
- def reverse(self):
- if self.head is None:
- return
- self.reverseUtil(self.head, None)
- def push(self, new_data):
- new_node = Node(new_data)
- new_node.next = self.head
- self.head = new_node
- def printList(self):
- temp = self.head
- while(temp):
- print(temp.data,end=" ")
- temp = temp.next
- llist = LinkedList()
- llist.push(8)
- llist.push(7)
- llist.push(6)
- llist.push(5)
- llist.push(4)
- llist.push(3)
- llist.push(2)
- llist.push(1)
- print("\n==================== Reverse a Linked List====================")
- print("\nMy list")
- llist.printList()
- llist.reverse()
- print("\n\nReverse linked list")
- llist.printList()
This script generates a star pattern resembling a Christmas tree. It uses nested loops to print different sections of the tree, including the triangular parts and the trunk. The program first displays a small triangular section, followed by progressively larger sections, then concludes with a trunk made of stars.
The script keeps running in a loop, allowing the user to repeat or exit the program based on their input (yes or no). Each loop iteration redraws the star pattern.
Output:

There you have it we successfully created How to Create Reverse a Linked List in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language