Circular Queue using linked list
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *newnode, *temp;
void enqueue(struct node **f, struct node **r)
{
int data,choice=1;
while(choice==1)
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data: ");
scanf("%d",&newnode->data);
newnode->next=0;
if(*f==0 && *r==0)
{
*f = newnode;
*r = newnode;
(*r)->next=*f;
// or (*r)->next=*r; that's same thing bcz there is only one node.
}
else
{
newnode->next=(*r)->next;
(*r)->next=newnode;
(*r)=newnode;
}
printf("want another element to be inserted(0,1): ");
scanf("%d",&choice);
}
}
void dequeue(struct node **f, struct node **r)
{
int choice=1;
while(choice==1)
{
if(*f==0 && *r==0)
{printf("Queue is Empty\n");break;}
else if(*f==*r)
{
printf("Deleted element is: %d",(*f)->data);
temp=*f;
free(temp);
*f=0;
*r=0;
}
else
{
printf("Deleted element is: %d",(*f)->data);
temp=*f;
*f=(*f)->next;
(*r)->next=*f; //You have to modify the link part of last node also;
free(temp);
}
printf("\nWant another element to be deleted(0,1): ");
scanf("%d",&choice);
}
}
void display(struct node *f, struct node *r)
{
temp=f;
if(f==0 && r==0)
printf("Queue is empty\n");
else
{
printf("Queue is:\n");
while(temp->next!=f)
{
printf("%d\n",temp->data);
temp=temp->next;
} // Loop will break before printing the last element because the last node will store the same value of front; //check the condition of loop;
printf("%d\n",temp->data);
}
}
void peek(struct node *f, struct node *r)
{
if(f==0 && r==0)
printf("Queue is empty\n");
else
printf("The element at the top of Queue is: %d\n", f->data);
}
int main()
{
int ch,choice=1;
struct node *frnt, *rear;
frnt=0;rear=0;
while(choice==1){
printf("\nEnter 1. to enqueue(insert in queue) \n");
printf("Enter 2. to dequeue (to delete from queue)\n");
printf("Enter 3. to display \n");
printf("Enter 4. to peek (to show the element at front) \n choice: ");
scanf("%d",&ch);
if(ch==1)
enqueue(&frnt, &rear);
else if(ch==2)
dequeue(&frnt, &rear);
else if(ch==3)
display(frnt, rear);
else if(ch==4)
peek(frnt, rear);
else
printf("invalid choice:");
printf("\nDo you want to continue(0,1): ");
scanf("%d",&choice);
}
}
Comments
Post a Comment