Here's an implementation of a basic Linked Queue in C
| #include <stdio.h> | |
| #include <stdlib.h> | |
| // Just use a singly linked list with f pointed to front of the queue | |
| // and r pointing to rear of the queue | |
| struct queue { | |
| int data; | |
| struct queue *next; | |
| }; | |
| struct queue *f, *r; | |
| void enqueue(int num) { | |
| struct queue *nn; | |
| nn = (struct queue *)malloc(sizeof(struct queue)); | |
| nn -> data = num; | |
| nn -> next = NULL; | |
| if(f == NULL) { | |
| f = r = nn; | |
| } else { | |
| r -> next = nn; | |
| r = nn; | |
| } | |
| } | |
| int dequeue() { | |
| int num; | |
| struct queue *temp; | |
| if(f == NULL) { | |
| return -1; | |
| } else { | |
| num = f -> data; | |
| temp = f; | |
| f = f -> next; | |
| free(temp); | |
| return num; | |
| } | |
| } | |
| void display() { | |
| struct queue *p; | |
| if(f == NULL) { | |
| printf("Queue is Empty\n"); | |
| } else { | |
| p = f; | |
| printf("The elements of the queue are: \n"); | |
| while(p != NULL) { | |
| printf("%d ", p -> data); | |
| p = p -> next; | |
| } | |
| printf("\n"); | |
| } | |
| } | |
| int main() | |
| { | |
| int num, choice, rpt = 1; | |
| while(rpt != 0) { | |
| printf("1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n"); | |
| printf("---------------\n"); | |
| printf("Enter a choice: "); | |
| scanf("%d", &choice); | |
| switch(choice) { | |
| case 1: | |
| printf("Enter a num: "); | |
| scanf("%d", &num); | |
| enqueue(num); | |
| break; | |
| case 2: | |
| num = dequeue(); | |
| if(num != -1) { | |
| printf("%d deleted from queue\n", num); | |
| } else { | |
| printf("Queue Underflow\n"); | |
| } | |
| break; | |
| case 3: | |
| display(); | |
| break; | |
| case 4: | |
| exit(0); | |
| } | |
| printf("Do you want to continue? (1/0): "); | |
| scanf("%d", &rpt); | |
| system("cls"); | |
| } | |
| return 0; | |
| } |
No comments:
Post a Comment