c code to reverse a queue by using stack

  • cstackqueue
  • write a c code to reverse a queue by using stack

    WAP using a function to reverse a queue by using stack.

    Code

    #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node *next; }; struct Node *s = NULL; struct Node *f = NULL; struct Node *r = NULL; void Display(struct Node *ptr) { printf("Printing the elements of this linked list\n"); while (ptr != NULL) { printf("Element: %d\n", ptr->data); ptr = ptr->next; } } int isEmpty(struct Node *top) { if (top == NULL) { return 1; } else { return 0; } } int isFull(struct Node *top) { struct Node *p = (struct Node *)malloc(sizeof(struct Node)); if (p == NULL) { return 1; } else { return 0; } } struct Node *push(struct Node *top, int x) { if (isFull(top)) { printf("Stack Overflow\n"); } else { struct Node *n = (struct Node *)malloc(sizeof(struct Node)); n->data = x; n->next = top; top = n; return top; } } int pop() { if (isEmpty(s)) { printf("Stack Underflow\n"); } else { struct Node *n = s; s = s->next; int x = n->data; free(n); return x; } } void enqueue(int val) { struct Node *n = (struct Node *)malloc(sizeof(struct Node)); if (n == NULL) { printf("Queue is Full"); } else { n->data = val; n->next = NULL; if (f == NULL) { f = r = n; } else { r->next = n; r = n; } } } int dequeue() { int val = -1; struct Node *ptr = f; if (f == NULL) { printf("Queue is Empty\n"); } else { f = f->next; val = ptr->data; free(ptr); } return val; } void reverse_queue_using_stack() { while (f != NULL) { s = push(s, dequeue()); } while (s != NULL) { enqueue(pop()); } } int main() { printf("enqueuing elements\n"); enqueue(34); enqueue(4); enqueue(7); enqueue(17); Display(f); reverse_queue_using_stack(); Display(f); return 0; }