C Program to Insert a node in circular linked list at Beginning
#include<conio.h> #include<stdio.h> #include<stdlib.h> struct node{ int data; struct node *next; }; struct node *head=NULL; struct node* createNode(){ struct node *newNode = (struct node *)malloc(sizeof(struct node)); return (newNode); } void insertNodeAtBegin(){ struct node *newNode, *temp, *ptr1, *ptr2; newNode=createNode(); printf("Enter a data to insert at begining:"); scanf("%d",&newNode->data); newNode->next=NULL; if(head==NULL){ head=newNode; head->next=head; } else{ ptr1=head; ptr2=head; while(ptr1->next!=head){ ptr1=ptr1->next; } ptr1->next=newNode; head=newNode; head->next=ptr2; } } void viewList(){ struct node* temp=head; if(temp==NULL){ printf("list is empty"); } else{ printf("Data in circular linked list are:\n"); while(temp->next!=head) { printf("%d\t",temp->data); temp=temp->next; } printf("%d \t",temp->data); } } int menu(){ int choice; printf("\n 1. Insert at begining"); printf("\n 2. Travesre/View List"); printf("\n 3. exit"); printf("\n Please enter your choice: \t"); scanf("%d",&choice); return(choice); } void main(){ while(1){ switch(menu()){ case 1: insertNodeAtBegin(); break; case 2: viewList(); break; case 3: exit(0); default: printf("invalid choice"); } getch(); } }
Output:

C Program to Insert a node in circular linked list at End
[cc]
#include
#include
#include
struct node{
int data;
struct node *next;
};
struct node *head=NULL;
struct node* createNode(){
struct node *newNode = (struct node *)malloc(sizeof(struct node));
return (newNode);
}
void insertNodeAtEnd(){
struct node *temp,*ptr;
temp=createNode();
printf(“Enter a data to insert at end:”);
scanf(“%d”,&temp->data);
temp->next=NULL;
if(head==NULL){
head=temp;
head->next=head;
}
else{
ptr=head;
while(ptr->next!=head){
ptr=ptr->next;
}
ptr->next=temp;
temp->next=head;
}
}
void viewList(){
struct node* temp=head;
if(temp==NULL){
printf(“list is empty”);
}
else{
printf(“Data in circular linked list are:\n”);
while(temp->next!=head)
{
printf(“%d\t”,temp->data);
temp=temp->next;
}
printf(“%d \t”,temp->data);
}
}
int menu(){
int choice;
printf(“\n 1. Insert at end”);
printf(“\n 2. Travesre/View List”);
printf(“\n 3. exit”);
printf(“\n Please enter your choice: \t”);
scanf(“%d”,&choice);
return(choice);
}
void main(){
while(1){
switch(menu()){
case 1:
insertNodeAtEnd();
break;
case 2:
viewList();
break;
case 3:
exit(0);
default:
printf(“invalid choice”);
}
getch();
}
}
[/cc]
Output:
