Sunday, November 8, 2015

Queue Implementation in C




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

struct node {
    int value;
    struct node *next;
};

typedef enum { false, true } bool;

void enqueue( struct node **head, struct node **rear, int val);
int dequeue( struct node **head, struct node **rear);
void display_queue( struct node **head, struct node **rear);
int queueSize( struct node **head, struct node **rear);
bool isEmpty( struct node **head, struct node **rear);


int main(){

struct node *head, *rear;

head = NULL;
rear = NULL;


enqueue_c( &head, &rear, 1);
enqueue_c( &head, &rear, 2);
enqueue_c( &head, &rear, 3);
enqueue_c( &head, &rear, 4);

display_queue_c(&head, &rear);

printf("[DEQUEUE] of QUEUE is %d\n", dequeue_c( &head, &rear));
printf("[DEQUEUE] of QUEUE is %d\n", dequeue_c( &head, &rear));
printf("[DEQUEUE] of QUEUE is %d\n", dequeue_c( &head, &rear));

display_queue_c(&head, &rear);


return 0;
}

void display_queue( struct node **head, struct node **rear){

    if( *head == NULL && *rear == NULL){
        printf("[QUEUE] is empty\n");
    } else {
        struct node *temp = *head;
        struct node *temp1 = *rear;
        while( temp != temp1){
            printf("[QUEUE] value is %d\n", temp->value);
            temp = temp->next;
        }
        if( temp1 != NULL){
            printf("[QUEUE] value is %d\n", temp1->value);
        }
    }

}

void enqueue( struct node **head, struct node **rear, int val ){

    if( *rear == NULL){
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp->value = val;
        temp->next = NULL;
        *rear = temp;
        *head = *rear;
    } else {
        struct node *temp = (struct node*)malloc(sizeof(struct node));
        temp->value = val;
        struct node *temp1 = *rear;
        temp1->next = temp;
        //printf("[DBG]: after modifying  %d\n", temp->value);
        *rear = temp;
    }
}


int dequeue(struct node **head, struct node **rear){

    if( *head == NULL){
        printf("[QUEUE] is empty\n");
        return -1;
    } else {
        struct node *temp = *head;
        struct node *temp1 = *head;
        temp1 = temp1->next;
        *head = temp1;
        return temp->value;
    }

}


int queueSize( struct node** head, struct node** rear){

    int count = 0;

    if( *head == NULL){
        printf("[QUEUE] is empty\n");
        return count;
    } else {
        struct node* temp ;
        temp = *head;
        while( temp != *rear){
            count += 1 ;
            temp = temp->next;
        }
        count++;
        return count;
    }
}


bool isEmpty( struct node** head, struct node** rear){

    if( *head == NULL && *rear == NULL){
        return true;
    }else{
        return false;
    }
}

No comments:

Post a Comment