Circular Queue, Circular linked list

/*linked list as circular queue*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};

void addq(struct node **f, struct node **r, int d);
void deleteq(struct node **f, struct node **r);
void display(struct node *f);

int main()
{
    struct node *front, *rear;
    front=rear=NULL;//initially que is empty

    addq(&front,&rear,10);
    addq(&front,&rear,20);
    addq(&front,&rear,30);
    addq(&front,&rear,40);
    addq(&front,&rear,50);

    display(front);//10 20 30 40 50
    deleteq(&front,&rear);
    display(front);//10 20 30 40 50
    deleteq(&front,&rear);
    display(front);//10 20 30 40 50
    printf("\n\n");
    return 0;
}

void addq(struct node **f, struct node **r, int d)
{
    struct node *newnode=(struct node *)malloc(sizeof(struct node));
    newnode->data=d;

    if(*f==NULL)//case 1:adding as first node if emty list
    {
        *f=newnode;
        *r=newnode;
    }
    else//case 2:adding at rear if not empty list
    {
        (*r)->next=newnode;
        *r=newnode;
    }
    (*r)->next=*f;//rear points to first as circular linked list
}

void display(struct node *f)
{
    printf("\ndisplay called:");
    struct node *current=f;
    struct node *ptr=NULL;
    while(current!=ptr)//ptr ise must.current must compare with first to NULL then with firsr
    {
        printf("%d ",current->data);
        current=current->next;
        ptr=f;
    }
}

void deleteq(struct node **f, struct node **r)
{
    printf("\ndelete called:");
    if(*f==NULL)
    {
        printf("\nNo element tp delete.\n");
    }
    else
    {
        struct node *temp;
        temp=*f;
        *f=(*f)->next;
        (*r)->next=*f;/* must else: first the first node gets deleted and 0 then 0 is deleted and garbage at first*/
        free(temp);
    }
}
/*
display called:10 20 30 40 50
delete called:
display called:20 30 40 50
delete called:
display called:30 40 50
*/

No comments:

Post a Comment