Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program For Rotating A Linked List
Next article icon

Python Program For Reversing A Doubly Linked List

Last Updated : 14 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.
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:

  1. Keep pushing the node's data in the stack. -> O(n)
  2. 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!

Next Article
Python Program For Rotating A Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • Python Programs
  • DSA
  • doubly linked list
Practice Tags :
  • Linked List

Similar Reads

  • Python Program For Rotating A Linked List
    Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in
    5 min read
  • Python Program For QuickSort On Doubly Linked List
    Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot. C/C++ Code """A typical recursive implementation of Quicksort for array """ """ This function takes last element as pivot, places the p
    5 min read
  • Python Program For Merge Sort For Doubly Linked List
    Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
    3 min read
  • Python Program For Searching An Element In A Linked List
    Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functi
    4 min read
  • Python Program For Removing Duplicates From A Sorted Linked List
    Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
    7 min read
  • Python Program For Reversing Alternate K Nodes In A Singly Linked List
    Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6-
    6 min read
  • Python Program For Flattening A Linked List
    Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it 'right' pointer in the code below).Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below). All linked l
    4 min read
  • Python Program For Deleting A Node In A Doubly Linked List
    Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
    4 min read
  • Python Program For Writing A Function To Delete A Linked List
    Algorithm For Python:In Python, automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null. Implementation:  C/C++ Code # Python3 program to delete all # the nodes of singly linked list # Node class class Node: # Function to initialize the # node object
    2 min read
  • Python Program For Printing Reverse Of A Linked List Without Actually Reversing
    Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorit
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences