Insert New node at the beginning of the Linked List
In this post, you will learn how to insert new node at the beginning of the Linked List, Code for the above task given below:
struct node{ int data; struct node *next;};struct node *head=NULL;
void insertElementAtBeginning(int val){struct node *New = malloc(sizeof(struct node));New->data = val;New->next = head;
head = New;}
In this program, we are doing following things:
- Creating a structure for node, which contains a value and pointer.
- After this we are creating a node head which is empty.
- Now allocating the memory in heap for the node New.
- Inserting the data in it and connecting to the next node that is head.
- After this we are making the New node head.
So this is how the function is working.
#include<stdio.h>#include<stdlib.h>
struct node{ int data; struct node *next;};
struct node *head = NULL;
void insertElementAtBeginning(int val){
struct node *New = malloc(sizeof(struct node));New->data = val;New->next = head;
head = New;}
void print(){ struct node *temp = head;
while(temp != NULL) { printf("%d ", temp->data); temp = temp->next; }}
int main(){
insertElementAtBeginning(1); insertElementAtBeginning(2); insertElementAtBeginning(3); print();
return 0;}