C Programming language

adplus-dvertising
C - Circular Linked List, Insert
Previous Home Next

Insertion in the circular linked list can be performed in the following ways :

  1. Insertion from the front i.e. insertion from the beginning of the list.
  2. Insertion from the back i.e. insertion from the last node of the list.
  3. Insertion from the specified position.

First two types of insertion operations are different than those of that of linear lists, but third one is exactly similar. So now we will write a program to show how can we perform these functions in a circular list.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
struct node
    {
int num;
struct node *next;
};                            /* declaring a global node of type struct */
typedef struct node NODE;    /* providing a type definition to the above created structure */
NODE *head=NULL;            /* declaring some of the global variable that would be used throughout the program */
NODE *temp, *first, *last;
int info;
void display();
void insert_at_end();
void insert_at_begin();
void main()                /* starting the main method() */
{
int i;
clrscr();
printf("\nprogram for insertion in a circular linked list :\n");
do
{
printf("\nEnter your choice :\n");     /*creating menu for various insertion operations on the list */
printf("\n1.Insert element at the end of the linklist :");
printf("\n2.Insert element at the begin of the linklist :");
printf("\n3.Exit\n");
fflush(stdin);
scanf("\n%d",&i);
switch(i)
{
case 1:
insert_at_end();
display();
break;
case 2:
insert_at_begin();
display();
break;
case 3:
exit(0);
}
}
while(i<=3);
getch();
}
void insert_at_end()
{
printf("\nEnter your element in the linked list :");
scanf("%d",&info);
temp=(NODE *)malloc(sizeof(NODE)); /* allocating memory for the node to be inserted */
temp->num=info;
temp->next=NULL;
if(head==NULL)                   /* checking whether list is empty */
{
temp->next=temp;
head=temp;
last=temp;
}
else
{
last->next=temp;
last=temp;
last->next=head;
}
}
void display()
{
if(head==NULL)
{
    printf("linked list is empty");
}
else
{
     first=head;
     printf("\nStatus of the linked list is as follows :\n");
 while(first->next!=head)        /* traversing the linked list */
      {
       printf("\n%d",first->num);
       first=first->next;
      }
}
}
void insert_at_begin()
{
printf("\nEnter the value which do you want to insert at begining\n");
scanf("\n%d"&info);
temp=(NODE *)malloc(sizeof(NODE));
temp->num=info;
if(head==NULL)
{
    temp->next=temp;
head=temp;
last=temp;
}
else
{
    temp->next=head;
head=temp;
last->next=head;
    }
}
Previous Home Next