0
0
DSA Pythonprogramming~30 mins

Reverse a Doubly Linked List in DSA Python - Build from Scratch

Choose your learning style9 modes available
Reverse a Doubly Linked List
📖 Scenario: You are working on a music playlist app. The playlist is stored as a doubly linked list where each node contains a song name. You want to add a feature to reverse the order of songs in the playlist.
🎯 Goal: Build a program that creates a doubly linked list of songs, then reverses the list, and finally prints the reversed playlist.
📋 What You'll Learn
Create a doubly linked list with exactly these songs in order: 'Song1', 'Song2', 'Song3', 'Song4'
Create a variable called head that points to the first node of the doubly linked list
Write a function called reverse_doubly_linked_list(head) that reverses the doubly linked list and returns the new head
Print the reversed doubly linked list in the format: Song4 <-> Song3 <-> Song2 <-> Song1 <-> None
💡 Why This Matters
🌍 Real World
Doubly linked lists are used in music players, browsers, and other apps where you need to move forward and backward through items efficiently.
💼 Career
Understanding linked lists and how to reverse them is a common interview question and helps build strong problem-solving skills in data structures.
Progress0 / 4 steps
1
Create the doubly linked list with songs
Create a class called Node with attributes data, prev, and next. Then create four nodes with data 'Song1', 'Song2', 'Song3', and 'Song4'. Link them to form a doubly linked list. Finally, create a variable called head that points to the first node.
DSA Python
Hint

Remember to link each node's next and prev attributes to form the doubly linked list.

2
Create a function to reverse the doubly linked list
Define a function called reverse_doubly_linked_list(head) that takes the head of the doubly linked list and reverses the list by swapping the next and prev pointers of each node. The function should return the new head of the reversed list.
DSA Python
Hint

Swap the prev and next pointers for each node. Move to the original next node by using the updated prev pointer.

3
Reverse the doubly linked list using the function
Call the function reverse_doubly_linked_list(head) and assign its result back to the variable head to update the head to the new reversed list.
DSA Python
Hint

Assign the result of reverse_doubly_linked_list(head) back to head.

4
Print the reversed doubly linked list
Write a loop to print the reversed doubly linked list starting from head. Print each node's data followed by ' <-> ' and end with 'None'. The output should look like: Song4 <-> Song3 <-> Song2 <-> Song1 <-> None
DSA Python
Hint

Use a while loop to traverse from head and print each node's data followed by ' <-> '. End with printing 'None'.