adding a node in the front on a linked list
Adding a Node in the Front of a Linked List in C
To add a node in the front of a linked list in C, you can follow these steps:
- Create a new node and assign the data value to it.
- Set the
next
pointer of the new node to point to the current head of the linked list. - Update the head pointer to point to the new node.
Here is an example implementation:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a node
struct Node {
int data;
struct Node* next;
};
// Function to add a node at the front of the linked list
void addNode(struct Node head, int data) {
// Create a new node
struct Node newNode = (struct Node)malloc(sizeof(struct Node));
newNode->data = data;
// Set the next pointer of the new node to the current head
newNode->next = *head;
// Update the head pointer to point to the new node
*head = newNode;
}
// Function to print the linked list
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// Test the implementation
int main() {
// Create an empty linked list
struct Node* head = NULL;
// Add nodes to the front of the linked list
addNode(&head, 3);
addNode(&head, 2);
addNode(&head, 1);
// Print the linked list
printList(head);
return 0;
}
This code creates a linked list and adds nodes with values 3, 2, and 1 to the front of the list. The addNode
function takes a double pointer to the head of the linked list as a parameter, allowing it to modify the head pointer. The printList
function is used to print the elements of the linked list.
When you run the code, the output will be:
1 2 3
This indicates that the nodes were successfully added to the front of the linked list in the correct order.