0

Circular Queue in C

Currently working on a code that gives us an integer value (1,2,3) along side with a datatype either integer/char/string. Here,

1 -> Enqueue
2 -> Dequeue
3 -> Display

For different testcases i am given with different data types. Like testcase 1 has integer values and testcase 2 with string names.

I need help in handling all the different input types for C. The following is my code for simple integer values.

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

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

struct node *head, *tail = NULL;

void enq(int x){
    struct node *nade = malloc(sizeof(struct node));
    nade->data = x;
    nade->next = head;
    if (head == NULL)
        head = tail = nade;
    else{
        tail->next = nade;
        tail = nade;
    }
}

void dq(){
    struct node *temp;
    if (head == NULL)
        printf("Deque is Empty\n");
    else if (head == tail){
        printf("%d is deleted\n", head->data);
        head = NULL;
    }
    else{
        printf("%d is deleted\n", head->data);
        tail->next = head->next;
        head = head->next;
    }
}

void display(){
    if (head == NULL)
        printf("Empty\n");
    else{
        struct node *temp;
        printf("Circular Queue ");
        for (temp = head; temp != tail; temp = temp->next)
            printf("%d ", temp->data);
        printf("%d\n", temp->data);
    }
}

int main(){
    int t; scanf("%d", &t);
    do{
        switch (t)
        {
        int x;
        case 1:
            scanf("%d", &x);
            enq(x);
            break;
        case 2:
            dq();
            break;
        case 3:
            display();
            break;
        }
        scanf("%d", &t);
    }while (t != 4);
    return 0;
} 
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • Try saving everything in string? – Ulire Ir Sep 07 '22 at 07:57
  • 1
    Start with avoiding `scanf()` for user input. use `fgets()`, and then parse and validate. – Sourav Ghosh Sep 07 '22 at 08:04
  • 1
    Grab paper and pencil to draw-out what you want to happen with these functions. The very first "enqueue" is not creating a "1 node" circular linked list. Things don't get any better after that... Study the problem, understand it so you know what is to be done at what point in each function, then reach for the keyboard. Try pushing 1 value into the 'queue' then displaying the entire queue (by continuous traversal 2 or 3 times.) – Fe2O3 Sep 07 '22 at 08:26
  • I'm afraid the first call to `enq()` will crash your program... – CiaPan Sep 08 '22 at 14:48
  • What's the point of 'Circularity' in your data structure? You don't seem to make any use of it. You try to keep `tail->next == head` but is serves literally _no purpose_ in your program. – CiaPan Sep 08 '22 at 14:55

0 Answers0