Python Program to Print the Doubly Linked List in Reverse OrderIn 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 -
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 StackWe can reverse the linked list using the stack as well. We will follow the below approach -
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). |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India