Bird
0
0
DSA Cprogramming~30 mins

Reverse a Doubly Linked List in DSA C - 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. Sometimes, users want to reverse the order of songs in their playlist.
🎯 Goal: Build a program that creates a doubly linked list with 3 songs, then reverses the list, and finally prints the reversed playlist.
📋 What You'll Learn
Create a doubly linked list with exactly 3 nodes containing the songs: "Song1", "Song2", "Song3" in that order
Create a pointer variable called head that points to the first node
Create a pointer variable called temp for swapping nodes during reversal
Write a function called reverseList that reverses the doubly linked list by swapping the next and prev pointers of each node
Print the reversed list starting from the new head using the printList function
💡 Why This Matters
🌍 Real World
Doubly linked lists are used in music players, browsers, and other apps where users navigate forward and backward through items.
💼 Career
Understanding linked lists and how to reverse them is a common interview question and helps in managing complex data structures efficiently.
Progress0 / 4 steps
1
Create the doubly linked list with 3 songs
Create a struct called Node with char* data, Node* next, and Node* prev. Then create 3 nodes with data "Song1", "Song2", and "Song3". Link them to form a doubly linked list. Create a pointer head that points to the first node.
DSA C
Hint

Remember to link the nodes both ways: next and prev.

2
Add a pointer variable temp for swapping
Inside main, declare a pointer variable called temp of type Node* and initialize it to NULL.
DSA C
Hint

Declare Node* temp = NULL; inside main.

3
Write the reverseList function to reverse the doubly linked list
Write a function called reverseList that takes a pointer head of type Node* and returns the new head after reversing the list. Inside the function, use a pointer temp to swap the next and prev pointers of each node. Update head to the last node after reversal. Call reverseList from main and update head.
DSA C
Hint

Swap next and prev for each node. Move current to prev after swapping. Update head to last node.

4
Print the reversed doubly linked list
Write a function called printList that takes head and prints the list data separated by arrows like: Song3 <-> Song2 <-> Song1. Call printList(head) from main after reversing the list.
DSA C
Hint

Traverse from head and print each node's data. Print <-> between nodes.