circular linked list
circular linked list
method one
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*start=NULL;
enum op{INSERT=1,DELETE,TRAVERSE,EXIT};
enum op1{BEG=1,POS,END};
int count =1;
void insert_beg(int data)
{
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
if(start == NULL)
{
start = newnode;
start->next = start;
}
else
{
struct node *temp = start;
while(temp->next != start)
temp = temp->next;
temp->next = newnode;
newnode->next=start;
start = newnode;
count++;
}
}
void insert_end(int data)
{
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
if(start == NULL)
{
start = newnode;
start->next = start;
}
else
{
struct node *temp = start;
while(temp->next != start)
temp = temp->next;
temp->next = newnode;
newnode->next = start;
count++;
}
}
void delete_end()
{
if(start==NULL)
{
printf("Nothing to deleted,as list is empty\n");
return;
}
else
{
struct node *ptr=start;
while(ptr->next->next!=start)
{
ptr = ptr->next;
}
struct node *ptr1=ptr->next;
ptr->next=start;
free(ptr1);
ptr = NULL;
count--;
}
}
void delete_beg()
{
if(start==NULL)
{
printf("Nothing to deleted,as list is empty\n");
return;
}
else
{
struct node *ptr=start;
while(ptr->next!=start)
{
ptr = ptr->next;
}
ptr->next= start->next;
ptr=start;
start = start->next;
free(ptr);
ptr=NULL;
count--;
}
}
void traverse()
{
if(start == NULL)
{
printf("Nothing to display as the list is empty\n");
return;
}
else
{
struct node *temp = start;
printf("\nThe linked list is : ");
while(temp->next!= start)
{
printf("%d-->",temp->data);
temp = temp->next;
}
printf("%d",temp->data);
}
}
void main()
{
int num,ch,pos,value,choice;
while(1)
{
printf("\n\nMENU\n1.Insert\n2.Delete\n3.Traverse\n4.Exit\n\n");
printf("Enter ur choice\n");
scanf("%d",&choice);
switch(choice)
{
case INSERT:
printf("\n\n1.Beg\n2.Pos\n3.End\n");
printf("Enter ur choice\n");
scanf("%d",&ch);
printf("\nEnter the data to be inserted\n");
scanf("%d",&num);
switch(ch)
{
case BEG: insert_beg(num);
break;
case POS:
// printf("Enter the position where u wan to insert\n");
// scanf("%d",&pos);
// insert_pos(num,pos);
break;
case END: insert_end(num);
break;
default:printf("Invalid choice\n");
}
break;
case DELETE: printf("\n\n1.Beg\n2.Pos\n3.End\n");
printf("Enter ur choice\n");
scanf("%d",&ch);
switch(ch)
{
case BEG: delete_beg();
break;
case POS:
// printf("Enter the position where u wan to insert\n");
// scanf("%d",&pos);
// delete_pos(pos);
break;
case END: delete_end();
break;
default:printf("Invalid choice\n");
}
break;
case TRAVERSE: traverse();
break;
case EXIT: exit(0);
default: printf("Invalid choice\n");
}
}
}
method 2
This comment has been removed by the author.
ReplyDelete