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
Selected Reading
Python program to rotate doubly linked list by N nodes
When working with doubly linked lists, rotation involves moving the first N nodes from the beginning to the end of the list. This requires a Node class with three attributes: data, next pointer, and previous pointer for bidirectional traversal.
Node Class Structure
Each node contains data and pointers to both next and previous nodes ?
class Node:
def __init__(self, my_data):
self.previous = None
self.data = my_data
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def add_data(self, my_data):
new_node = Node(my_data)
if self.head is None:
self.head = self.tail = new_node
else:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
self.size += 1
def print_list(self):
curr = self.head
if curr is None:
print("The list is empty")
return
print("The nodes in the doubly linked list are:")
while curr is not None:
print(curr.data)
curr = curr.next
def rotate_list(self, n):
if n == 0 or n >= self.size or self.head is None:
return
# Find the nth node
curr = self.head
for i in range(1, n):
curr = curr.next
# Store new head
new_head = curr.next
# Break the connection and rotate
self.tail.next = self.head
self.head.previous = self.tail
self.head = new_head
self.head.previous = None
self.tail = curr
self.tail.next = None
# Example usage
dll = DoublyLinkedList()
print("Elements are being added to the doubly linked list")
dll.add_data(10)
dll.add_data(24)
dll.add_data(54)
dll.add_data(77)
dll.add_data(24)
dll.add_data(0)
dll.print_list()
print("\nThe elements in the list after rotating by 4 nodes:")
dll.rotate_list(4)
dll.print_list()
Elements are being added to the doubly linked list The nodes in the doubly linked list are: 10 24 54 77 24 0 The elements in the list after rotating by 4 nodes: The nodes in the doubly linked list are: 24 0 10 24 54 77
How the Rotation Works
The rotation algorithm follows these steps ?
- Find the nth node from the beginning
- The (n+1)th node becomes the new head
- Connect the original tail to the original head
- Update head and tail pointers accordingly
Visualization
Key Points
- Edge Cases: Handle empty lists and rotation values greater than list size
- Bidirectional Links: Update both next and previous pointers during rotation
- Circular Connection: Temporarily connect tail to head during rotation
- Pointer Management: Carefully update head and tail references
Conclusion
Rotating a doubly linked list by N nodes involves finding the split point, reconnecting pointers, and updating head/tail references. The algorithm maintains the bidirectional nature of the list while efficiently repositioning elements.
Advertisements
