Insert New node at the beginning of the Doubly Linked List
In this post, you will learn how to insert new node at the beginning of the Doubly Linked List, Code for the above task given below:
struct node{ struct node *prev;
int data; struct node *next;};
struct node *head = NULL;
void insertElementAtBeginning(int val){
struct node *new = malloc(sizeof(struct node));
new->data=val;
if(head==NULL){
new->prev=NULL;
new->next=NULL;
head = new;
}
else{
new->prev=NULL;
new->next=head;
head->prev=new;
head = new;
}
}
In this program, we are doing following things:
- Creating a structure for node, which contains a value and two pointer.
- After this we are checking if the head is empty so make the new node head.
- If the head is not empty then make the new node previous pointer null and next pointer points to head and make the head prev node points to next of new node.
- After this make the new node as head.
- This is how we insert at the beginning.
So this is how the function is working.
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
struct node *prev;
};
struct node *head = NULL;
void insertAtBeginning(int a){
struct node *new = malloc(sizeof(struct node));
new->data = a;
if(head==NULL){
new->next = NULL;
new->prev = NULL;
head = new;
}
else{
new->prev = NULL;
new->next = head;
head->prev = new;
head = new;
}
}
void print()
{
struct node *p = head;
while(p!= NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
int main()
{
insertAtBeginning(10);
insertAtBeginning(20);
insertAtBeginning(30);
print();
return 0;
}