Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to create a doubly linked list of n nodes and display it in reverse order
A doubly linked list is a data structure where each node contains data and pointers to both the next and previous nodes. To create and reverse a doubly linked list, we need to define a Node class and a list class with methods for adding nodes and reversing the order.
Node Class Structure
The Node class contains three attributes: data, next pointer, and previous pointer ?
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
Doubly Linked List Implementation
The main class manages the list with head and tail pointers, and methods for adding nodes, reversing, and displaying ?
class Node:
def __init__(self, my_data):
self.prev = None
self.data = my_data
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_data(self, my_data):
new_node = Node(my_data)
if self.head == None:
self.head = self.tail = new_node
self.head.prev = None
self.tail.next = None
else:
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
self.tail.next = None
def reverse_vals(self):
curr = self.head
while curr != None:
temp = curr.next
curr.next = curr.prev
curr.prev = temp
curr = curr.prev
# Swap head and tail
temp = self.head
self.head = self.tail
self.tail = temp
def print_it(self):
curr = self.head
if self.head == None:
print("The list is empty")
return
print("The nodes are:")
while curr != None:
print(curr.data)
curr = curr.next
# Create and test the doubly linked list
my_list = DoublyLinkedList()
print("Elements are being added to the list")
my_list.add_data(10)
my_list.add_data(14)
my_list.add_data(24)
my_list.add_data(17)
my_list.add_data(22)
print("\nOriginal list:")
my_list.print_it()
print("\nAfter reversing:")
my_list.reverse_vals()
my_list.print_it()
Elements are being added to the list Original list: The nodes are: 10 14 24 17 22 After reversing: The nodes are: 22 17 24 14 10
How the Reversal Works
The reversal algorithm swaps the next and prev pointers of each node, then swaps the head and tail pointers ?
Key Methods Explained
add_data() Method
Adds a new node at the end of the list, updating both next and previous pointers ?
reverse_vals() Method
Swaps the next and prev pointers of each node, then swaps head and tail to complete the reversal ?
print_it() Method
Traverses the list from head to tail and displays each node's data ?
Conclusion
Creating a doubly linked list requires careful management of both forward and backward pointers. The reversal algorithm efficiently swaps pointer directions and updates head/tail references to reverse the entire list structure.
