Created
July 23, 2020 13:45
-
-
Save uhmseohun/5e3fa04a4b574463b7b1f2d3550259d0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#define QUEUE_SIZE 5 | |
typedef char element; | |
typedef struct { | |
element queue[QUEUE_SIZE]; | |
int front, rear; | |
} QueueType; | |
QueueType* createQueue() { | |
QueueType* cQ; | |
cQ = (QueueType*)malloc(sizeof(QueueType)); | |
cQ -> front = 0; | |
cQ -> rear = 0; | |
return cQ; | |
} | |
int isEmpty(QueueType *cQ) { | |
return cQ -> front == cQ -> rear; | |
} | |
int isFull(QueueType* cQ) { | |
return (cQ -> front + 1) % QUEUE_SIZE == cQ -> front; | |
} | |
void enQueue(QueueType* cQ, element item) { | |
if(isFull(cQ)) exit(0); | |
cQ -> rear = (cQ -> rear + 1) % QUEUE_SIZE; | |
cQ -> queue[cQ -> rear] = item; | |
} | |
element deQueue(QueueType* cQ) { | |
if(isEmpty(cQ)) exit(0); | |
cQ -> front = (cQ -> front + 1) % QUEUE_SIZE; | |
return cQ -> queue[cQ -> front]; | |
} | |
element peek(QueueType* cQ) { | |
if(isEmpty(cQ)) exit(0); | |
return cQ -> queue[(cQ -> front + 1) % QUEUE_SIZE]; | |
} | |
void print(QueueType *cQ) { | |
int first = (cQ -> front + 1) % QUEUE_SIZE; | |
int last = (cQ -> rear + 1) % QUEUE_SIZE; | |
int i = first; | |
printf("Queue: {"); | |
while(i != last) { | |
printf("%3c", cQ -> queue[i]); | |
i = (i + 1) % QUEUE_SIZE; | |
} | |
printf(" }\n"); | |
} | |
int main() { | |
QueueType* cQ = createQueue(); | |
printf("A -> EnQueue: "); | |
enQueue(cQ, 'A'); | |
print(cQ); | |
printf("B -> EnQueue: "); | |
enQueue(cQ, 'B'); | |
print(cQ); | |
printf("C -> EnQueue: "); | |
enQueue(cQ, 'C'); | |
print(cQ); | |
printf("Peek -> %c\n", peek(cQ)); | |
printf("DeQueue -> %c\n", deQueue(cQ)); | |
print(cQ); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment