Insert A Node At End of A Circular Linked List In C

Hello Coders! In this post, you will learn how to insert new node at the end of the Circular Linked List, Code for the above task given below:

How To Insert A Node At End of A Circular Linked List In C ?

``````struct node{
int data;
struct node *next;

};

void insertAtEnd(int a){
struct node *new = malloc(sizeof(struct node));
new->data = a;

new->next=new;

}

else{

while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next = new;
}
}``````

In this code we are doing following things:

1. If linked list is empty then make the node as head and its next pointer points to itself.
2. Else make a new pointer say temp which iterates from first to last node.
3. Then insert the node at the end of the linked list and points to the previous head.
4. So this is how we insert a new node at the beginnig of the circular linked list.

So this is how the function is working.

``````#include<stdio.h>
#include<stdlib.h>

struct node{
int data;
struct node *next;

};

void insertAtEnd(int a){
struct node *new = malloc(sizeof(struct node));
new->data = a;

new->next=new;

}

else{

while (temp->next!=NULL)
{
temp = temp->next;
}

temp->next = new;

}
}

void print()
{
while(temp != NULL)
{
printf("%d ", p->data);
p = p->next;
}
}

int main()
{

insertAtEnd(1);
insertAtEnd(2);
insertAtEnd(3);
print();

return 0;
}``````