Queue Using Linked List

 avatar
kaziamir
c_cpp
a year ago
1.6 kB
4
Indexable
Never
/*  This code is the code for implimenting Queue using Linked List. 
    N.B: I used char type data in for node   */

#include<stdio.h>
#include<stdlib.h>

typedef struct node{
    char data;
    struct node *next;
}node;

node *frnt = NULL, *rear = NULL;

void enque(char x){
    node *newNode = (node *)malloc(sizeof(node));
    if(newNode!=NULL){
        newNode->data = x;
        newNode->next = NULL;
        if(rear==NULL){
            frnt = newNode;
            rear = newNode;
        }
        else{
            rear->next = newNode;
            rear = newNode;
        }
        printf("%c Enqued.\n", x);
    }
    else{
        printf("Queue overflow\n");
    }
}

void deque(){
    if(frnt!=NULL){
        node *tmp = frnt;
        frnt = frnt->next;
        printf("%c Dequed.\n", tmp->data);
        free(tmp);
        if(frnt==NULL){
            rear = NULL;
        }
    }
    else{
        printf("Queue Underflow\n");
    }
}

void display(){
    if(frnt!=NULL){
        printf("Current Queue: ");
        node *p = frnt;
        while(p!=NULL){
            printf("%c ",p->data);
            p = p->next;
        }
        printf("\n");
    }
    else{
        printf("Queue Empty\n");
    }
}

int main(){
    enque('W');
    display();
    enque('X');
    display();
    enque('Y');
    display();
    enque('Z');
    display();
    deque();
    display();
    deque();
    display();
    deque();
    display();
    enque('A');
    display();
    deque();
    display();
    deque();
    display();
    deque();
    display();

    return 0;
}