Deque Using Linked List

 avatar
kaziamir
c_cpp
6 months ago
2.6 kB
2
Indexable
Never
/*  This code is the code for implimenting DEQUE using Linked List. 
    N.B: I used char type data for node   */

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

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

node *left = NULL, *right = NULL;

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

void enqueRight(char x){
    node *newNode = (node *)malloc(sizeof(node));
    if(newNode!=NULL){
        newNode->data = x;
        newNode->next = NULL;
        if(right==NULL){
            right = newNode;
            left = newNode;
        }
        else{
            right->next = newNode;
            right = newNode;
        }
        printf("%c Enqued at Right\n", x);
    }
    else{
        printf("Queue overflow\n");
    }
}

void dequeLeft(){
    if(left!=NULL){
        node *tmp = left;
        left = left->next;
        printf("%c Dequed from left\n", tmp->data);
        free(tmp);
        if(left==NULL){
            right = NULL;
        }
    }
    else{
        printf("Queue Underflow\n");
    }
}

void dequeRight(){
    if(right!=NULL){
        node *tmp = right;
        node *p = left;
        if(left==right){
            left = NULL;
            right = NULL;
        }
        else{
            while(p->next!=right){
                p = p->next;
            }
            p->next = NULL;
            right = p;
        }
        printf("%c Dequed from left\n", tmp->data);
        free(tmp);
        
    }
    else{
        printf("Queue Underflow\n");
    }
}

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

int main(){
    enqueLeft('W');
    display();
    enqueLeft('X');
    display();
    enqueRight('Y');
    display();
    enqueRight('Z');
    display();
    /*dequeLeft();
    display();
    dequeLeft();
    display();
    dequeLeft();
    display();
    dequeLeft();
    display();
    dequeLeft();
    display();*/
    dequeRight();
    display();
    dequeRight();
    display();
    dequeRight();
    display();
    dequeRight();
    display();
    dequeRight();
    display();
    dequeRight();
    display();

    return 0;
}