0
0
DSA Pythonprogramming~30 mins

Insert at Beginning of Doubly Linked List in DSA Python - Build from Scratch

Choose your learning style9 modes available
Insert at Beginning of Doubly Linked List
📖 Scenario: You are managing a playlist of songs where each song knows the previous and next song. You want to add a new song at the start of the playlist.
🎯 Goal: Build a doubly linked list and insert a new node at the beginning, then print the list from start to end.
📋 What You'll Learn
Create a Node class with data, prev, and next attributes
Create a DoublyLinkedList class with a head attribute
Implement a method insert_at_beginning(data) to add a node at the start
Implement a method print_list() to print the list from head to end
💡 Why This Matters
🌍 Real World
Doubly linked lists are used in music players, browsers, and undo-redo systems where you need to move forward and backward easily.
💼 Career
Understanding linked lists is fundamental for software engineering roles, especially for working with complex data structures and memory management.
Progress0 / 4 steps
1
Create Node and DoublyLinkedList classes
Create a Node class with an __init__ method that sets data, prev, and next attributes. Then create a DoublyLinkedList class with an __init__ method that sets head to None.
DSA Python
Hint

Define two classes. The Node holds data and links. The DoublyLinkedList starts empty with head = None.

2
Add insert_at_beginning method
Inside the DoublyLinkedList class, add a method called insert_at_beginning(self, data). This method should create a new Node with the given data. If the list is empty (head is None), set head to the new node. Otherwise, set the new node's next to the current head, set the current head's prev to the new node, and update head to the new node.
DSA Python
Hint

Create a new node. If list empty, set head to new node. Else, link new node before current head and update head.

3
Add print_list method
Inside the DoublyLinkedList class, add a method called print_list(self). This method should start from head and print each node's data followed by -> until the end of the list is reached. After the last node, print None.
DSA Python
Hint

Start from head and move next until None, printing each data with arrows.

4
Insert nodes and print the list
Create a DoublyLinkedList object called dll. Use insert_at_beginning to add nodes with data 10, 20, and 30 in that order. Then call dll.print_list() to display the list.
DSA Python
Hint

Create the list object, insert 10, then 20, then 30 at beginning, then print.