0
0
DSA Pythonprogramming~30 mins

Insert at Beginning Head Insert in DSA Python - Build from Scratch

Choose your learning style9 modes available
Insert at Beginning (Head Insert) in a Linked List
📖 Scenario: Imagine you are managing a line of people waiting to enter a concert. Sometimes, a VIP arrives and needs to be placed right at the front of the line. We will simulate this using a linked list where each person is a node.
🎯 Goal: You will build a simple linked list and learn how to insert a new node at the beginning (head) of the list. This means the new person will be first in line.
📋 What You'll Learn
Create a Node class with data and next attributes
Create a LinkedList class with a head attribute
Write a method insert_at_beginning to add a new node at the start
Print the linked list after insertion to show the order
💡 Why This Matters
🌍 Real World
Linked lists are used in many applications like music playlists, undo functionality in apps, and managing queues where order matters.
💼 Career
Understanding linked lists and how to insert nodes is fundamental for software developers, especially when working with dynamic data structures and memory management.
Progress0 / 4 steps
1
Create Node and LinkedList classes
Create a class called Node with an __init__ method that takes data and sets self.data = data and self.next = None. Then create a class called LinkedList with an __init__ method that sets self.head = None.
DSA Python
Hint

Think of Node as a person in line holding data and a pointer to the next person. The LinkedList keeps track of the first person with head.

2
Add insert_at_beginning method
Inside the LinkedList class, define a method called insert_at_beginning that takes self and data. Create a new Node with data. Set the new node's next to the current head. Then update head to the new node.
DSA Python
Hint

Remember, the new node points to the old first node, then becomes the new first node.

3
Add method to print the linked list
Inside the LinkedList class, define a method called print_list that takes self. Use a variable current starting at head. Use a while loop to print current.data followed by ' -> ' and move current to current.next. After the loop, print None.
DSA Python
Hint

Traverse the list from head to end, printing each node's data followed by an arrow.

4
Insert nodes and print the list
Create a LinkedList object called ll. Use ll.insert_at_beginning(30), then ll.insert_at_beginning(20), then ll.insert_at_beginning(10). Finally, call ll.print_list() to display the list.
DSA Python
Hint

Insert 30 first, then 20 before it, then 10 before 20. The list should print from 10 to 30.