Insert Node At The Beginning of The Circular Linked List
In this post, you will learn how you can insert a node at the beginning of the circular linked list.
Code
struct node{
int data;
struct node *next;
};
struct node *head = NULL;
void insertAtBeginning(int a){
struct node *new = malloc(sizeof(struct node));
new->data = a;
if(head==NULL){
new->next=new;
head = new;
}
else{
struct node *temp = head;
while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next = new;
new->next = head;
head = new;
}
}
In this code we are doing following things:
- If linked list is empty then make the node as head and its next pointer points to itself.
- Else make a new pointer say temp which iterates from first to last node.
- Then insert the node at the end of the linked list and make the last node as head which points to previous head.
- So this is how we insert a new node at the beginnig of the circular linked list.
#include<stdio.h>#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head = NULL;
void insertAtBeginning(int a){
struct node *new = malloc(sizeof(struct node));
new->data = a;
if(head==NULL){
new->next=new;
head = new;
}
else{
struct node *temp = head;
while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next = new;
new->next = head;
head = new;
}
}
void print()
{
struct node *p = head;
while(temp != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}
int main(){
insertAtBeginning(1); insertAtBeginning(2); insertAtBeginning(3); print();
return 0;}