Thursday, April 9, 2015

[Data Structures] Queue with list in C

Here is Queue data structure with Linked List in C programming language.



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

typedef struct Node {
    struct Node* Next;
    int data;
} Node;

Node *front,*rear;

void initQue(void);
void enque(int);
bool deque(int *);
void printQue();

int main(int argc, const char * argv[]) {
    int input=0;
    initQue();
    while(true) {
        printf("Queue with List Program\n");
        printf("1. Enque\n");
        printf("2. Deque\n");
        printf("3. Print Que\n");
        printf("4. Exit\n");
        printf("Enter your command : ");
        scanf("%d",&input);
        getchar();
        
        switch (input) {
            case 1:
                printf("Enter a data : ");
                scanf("%d",&input);
                getchar();
                enque(input);
                break;
            case 2:
                if(deque(&input)) {
                    printf("Data is %d.\n",input);
                } else {
                    printf("Que is empty.\n");
                }
                break;
            case 3:
                printQue();
                break;
            case 4:
                exit(0);
            default:
                break;
        }
    }

    return 0;
}

void initQue(void) {
    front = (Node *)malloc(sizeof(Node));
    rear = (Node *)malloc(sizeof(Node));
    front->Next = rear;
    rear->Next = rear;
}

void enque(int data) {
    Node *tempNode = (Node *)malloc(sizeof(Node));
    tempNode->data = data;
    if(front->Next==rear) {
        front->Next = tempNode;
        tempNode->Next = rear;
        rear->Next = tempNode;
    } else {
        rear->Next->Next = tempNode;
        tempNode->Next = rear;
        rear->Next = tempNode;
    }
}

bool deque(int *data) {
    if(front->Next==rear) {
        return false;
    }
    Node *tempNode = front->Next;
    *data = tempNode->data;
    front->Next = tempNode->Next;
    free(tempNode);
    return true;
}

void printQue() {
    Node *currentNode = front->Next;
    if(front->Next==rear) {
        printf("Que is empty.\n");
        return;
    }
    printf("Front -> ");
    while(currentNode!=rear) {
        printf("%d -> ",currentNode->data);
        currentNode = currentNode->Next;
    }
    printf("Rear\n");
}






No comments:

Post a Comment