Python Program For Reversing A Doubly Linked List
Last Updated :
14 Dec, 2021
Given a Doubly Linked List, the task is to reverse the given Doubly Linked List.
See below diagrams for example.
(a) Original Doubly Linked List

(b) Reversed Doubly Linked List
Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes, change prev of the head (or start) and change the head pointer in the end.
Python
# Program to reverse a doubly linked list
# A node of the doubly linked list
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
# Constructor for empty Doubly
# Linked List
def __init__(self):
self.head = None
# Function reverse a Doubly Linked List
def reverse(self):
temp = None
current = self.head
# Swap next and prev for all nodes
# of doubly linked list
while current is not None:
temp = current.prev
current.prev = current.next
current.next = temp
current = current.prev
# Before changing head, check for the
# cases like empty list and list with
# only one node
if temp is not None:
self.head = temp.prev
# Given a reference to the head of a list
# and an integer,inserts a new node on the
# front of list
def push(self, new_data):
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
# 3. Make next of new node as head
# and previous as None (already None)
new_node.next = self.head
# 4. change prev of head node to
# new_node
if self.head is not None:
self.head.prev = new_node
# 5. move the head to point to the
# new node
self.head = new_node
def printList(self, node):
while(node is not None):
print node.data,
node = node.next
# Driver code
dll = DoublyLinkedList()
dll.push(2)
dll.push(4)
dll.push(8)
dll.push(10)
print
"Original Linked List"
dll.printList(dll.head)
# Reverse doubly linked list
dll.reverse()
print
"Reversed Linked List"
dll.printList(dll.head)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Original linked list
10 8 4 2
The reversed Linked List is
2 4 8 10
Time Complexity: O(N), where N denotes the number of nodes in the doubly linked list.
Auxiliary Space: O(1)
We can also swap data instead of pointers to reverse the Doubly Linked List. Method used for reversing array can be used to swap data. Swapping data can be costly compared to pointers if the size of the data item(s) is more.
Please write comments if you find any of the above codes/algorithms incorrect, or find better ways to solve the same problem.
Method 2:
The same question can also be done by using Stacks.
Steps:
- Keep pushing the node's data in the stack. -> O(n)
- The keep popping the elements out and updating the Doubly Linked List
Python3
"""
Function to reverse a doubly-linked list
swap next and prev pointers for all the
nodes change prev of the head node
change head pointer
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
"""
Method to reverse a Doubly-Linked List
using Stacks
"""
def reverseUsingStacks(self):
stack = []
temp = self.head
while temp is not None:
stack.append(temp.data)
temp = temp.next
# Add all the elements in the stack
# in a sequence to the stack
temp = self.head
while temp is not None:
temp.data = stack.pop()
temp = temp.next
# Popped all the elements and the
# added in the linked list,
# in a reversed order.
"""
Method to push a new item before
the head
"""
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
if self.head is not None:
self.head.prev = new_node
self.head = new_node
"""
Method to traverse the doubly-linked
list and print every node in the list
"""
def printList(self, node):
while(node is not None):
print(node.data)
node = node. next
# Driver code
dll = DoublyLinkedList()
dll.push(2)
dll.push(4)
dll.push(8)
dll.push(10)
print(
"original doubly-linked list")
dll.printList(dll.head)
# Reverse a doubly-linked list
dll.reverseUsingStacks()
print("Reversed doubly-linked list")
dll.printList(dll.head)
Output:
Original linked list
10 8 4 2
The reversed Linked List is
2 4 8 10
Time Complexity: O(N)
Auxiliary Space: O(N)
In this method, we traverse the linked list once and add elements to the stack, and again traverse the whole for updating all the elements. The whole takes 2n time, which is the time complexity of O(n).
Please refer complete article on
Reverse a Doubly Linked List for more details!
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read