Complete Circular Singly linked list using C
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int data;
struct node * next;
};
struct node *head, *newnode, *tail, *temp, *stemp;
int count=0,f=1; // f==1 means that list is not created or became empty
void create()
{
head =0;
tail=0;
int choice=1;
while(choice==1)
{
count++;
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter data");
scanf("%d",&newnode->data);
if(head==0)
{
head=newnode;
tail=newnode;
newnode->next=newnode;
}
else
{
tail->next=newnode;
tail= newnode;
tail->next=head;
}
printf("want another node (0,1): ");
scanf("%d",&choice);
}
}
void insrt()
{
int pos,i;
count++;
printf("\nenter the position of insertion");
scanf("%d",&pos);
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter data");
scanf("%d",&newnode->data);
//forming link
if(pos==1)//at beginning
{
newnode->next=head;
tail->next=newnode;
head=newnode;
}
else if(pos==count)//at end
{
newnode->next=tail->next;
tail->next=newnode;
tail=newnode;
}
else //at some position in middle
{
i=1;
temp=head;
while(i<pos-1)
{
temp=temp->next;
i++;
}
newnode->next=temp->next;
temp->next=newnode;
}
}
void delpos(int pos)
{
int i;
temp=head;
if(temp->next==tail->next) // if only one node is present in list.
{
printf("this was the last node of the list");
tail=0;
head=0;
free(temp);
}
else
{
if(pos==1)
{
temp=head;
head=temp->next;
free(temp);
}
else if(pos==count)
{
temp=head;
while(temp!=tail)
{
stemp=temp;
temp=temp->next;
}
stemp->next=tail->next;
tail=stemp;
free(temp);
}
else
{
i=0;
temp=head;
while(i<pos-1)
{
stemp=temp;
temp=temp->next;
i++;
}
stemp->next=temp->next;
free(temp);
}
}
}
void print()
{
temp=head;
printf("printing the list of size : %d\n",count);
while(temp!=tail)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("%d",temp->data); // this is to print the last node;
}
int main()
{
int choice,conti=1,pos;
f=1;
while(conti==1)
{
printf("Press 1. to create list");
printf("\nPress 2. to insert in list");
printf("\nPress 3. to delete in list");
printf("\nPress 4. to print list");
printf("\nEnter your choice: ");
scanf("%d",&choice);
if(choice==1)
{
if(f==1)
{create();f=0;}
else
printf("list already created");
}
else if(f==1)
printf("list is empty, create list first");
else
{
if(choice==2)
insrt();
else if(choice==3)
{
printf("enter the position of deletion: ");
scanf("%d",&pos);
if(pos>count)
printf("invalid position");
else{
delpos(pos);
count-=1;
if(count==0)
f=1;
}
}
else if(choice==4)
print();
else
printf("invalid choice");
}
printf("\nDo you want to continue(0,1): ");
scanf("%d",&conti);
}
}
Comments
Post a Comment