Bird
0
0
DSA Cprogramming~30 mins

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

Choose your learning style9 modes available
Insert at Beginning (Head Insert) in a Linked List
📖 Scenario: Imagine you are managing a guest list for a party. New guests arrive and you want to add each new guest to the front of the list so they are greeted first.
🎯 Goal: You will build a simple linked list in C and learn how to insert new nodes at the beginning (head) of the list.
📋 What You'll Learn
Create a linked list node structure with an integer data field and a next pointer
Create a pointer head to represent the start of the list
Write a function insertAtBeginning to add a new node at the start
Insert three nodes with values 10, 20, and 30 at the beginning in that order
Print the linked list after all insertions showing the order of nodes
💡 Why This Matters
🌍 Real World
Linked lists are used in many applications like managing playlists, undo functionality in apps, and dynamic memory management.
💼 Career
Understanding linked lists and how to insert nodes is fundamental for software developers working with data structures and memory management.
Progress0 / 4 steps
1
Create the linked list node structure and initialize head
Write the struct definition for a linked list node named Node with an int data and a Node* pointer named next. Then create a Node* variable called head and initialize it to NULL.
DSA C
Hint

Use typedef struct Node { int data; struct Node* next; } Node; and set head to NULL.

2
Create the insertAtBeginning function
Write a function called insertAtBeginning that takes an int value parameter. Inside, create a new Node* using malloc, set its data to value, set its next to the current head, then update head to this new node.
DSA C
Hint

Allocate memory for a new node, set its data, point its next to head, then update head.

3
Insert nodes with values 10, 20, and 30 at the beginning
Call the insertAtBeginning function three times to insert the values 10, 20, and 30 in that order.
DSA C
Hint

Call insertAtBeginning three times with 10, 20, and 30.

4
Print the linked list to show the order of nodes
Write a printList function that starts from head and prints each node's data followed by ->. After printing all nodes, print NULL. Then call printList() in main after the insertions.
DSA C
Hint

Traverse from head, print each node's data followed by '->', then print 'NULL'.