Javatpoint Logo
Javatpoint Logo

Python Program to Print the Doubly Linked List in Reverse Order

In this tutorial, we will write the Python program to print the reversed linked list. Doubly-linked list is a circular linked list which creates the circular linked list. To solve this problem we will use the following steps -

  • Traverse the linked list using a pointer
  • Swap the prev and next pointers for all nodes
  • At last, change the head pointer of the doubly linked list

Example -

Output -

Print Doubly Linked list 
Nodes of doubly linked list: 
4
2
8
1
5
12
Print Reversed Doubly Linked List
12
5
1
8
2
4

Explanation -

In the above code, we have created the class Node that initialized the singly linked list. To create the doubly linked list, we initialized the doubly linked list class where we assigned the initial value of the head, prev and next as none and count as zero. We defined the insert_element() function which call the Node class to insert the elements. First we check if the head is none, insert the new item to head and assign the head into tail.

Otherwise, we assigned the tail to new_item.pre, new node to tail.next and tail. We increased the count as one on every insertion of the element.

In the reverse() function, we assign the current variable that holds the head of the list. We checked if double-linked list is non-empty, we store the current's next into temp variable and traverse the doubly linked list, we assign the current's prev to the current's next and temp to current's prev.

At the end of the code we created the object of the Doubly_Linked_List class and insert the elements to the list. We called the print_list() method to print the simple doubly linked list and called reverse() function to print reverse of the linked list.

The time complexity will be O(N) where N represents the number of nodes in the doubly linked list and auxiliary space will be O(N).

Reverse the Doubly Linked List using Stack

We can reverse the linked list using the stack as well. We will follow the below approach -

  • First, we traverse the linked list and push the node's data into the stack.
  • Then keep popping the elements out of the stack and updating the Doubly Linked List.

Let's implement the above approach into the Python code -

Example -

Output -

Print Doubly Linked list 
Nodes of doubly linked list: 
4
2
8
1
5
12
Print Reversed Doubly Linked List
12
5
1
8
2
4

The time complexity will be O(N) and auxiliary space will be O(N).







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA