c code for stack using queue.

  • cstack_using_queue
  • write a c code for stack using queue.

    A queue data structure is given with enqueue and dequeue operations. WAP to implement a stack using instances of queue data structure and operations on them

    Code

    #include <stdio.h> #include <stdlib.h> struct queue { int size; int f; int r; int *arr; }; int isEmpty(struct queue *q) { if (q->r == q->f) { return 1; } return 0; } int isFull(struct queue *q) { if (q->r == q->size - 1) { return 1; } return 0; } void enqueue(struct queue *q, int val) { if (isFull(q)) { printf("This Queue is full\n"); } else { q->r++; q->arr[q->r] = val; } } int dequeue(struct queue *q) { int a = -1; if (isEmpty(q)) { printf("This Queue is empty\n"); } else { q->f++; a = q->arr[q->f]; } return a; } void push(struct queue *q, int val) { if (isFull(q)) { printf("Stack Overflow! Cannot push %d to the Stack\n", val); } else { enqueue(q, val); } } int pop(struct queue *q) { struct queue qT; qT.size = q->size-1; qT.f = qT.r = 0; qT.arr = (int *)malloc(qT.size * sizeof(int)); int x; if (isEmpty(q)) { printf("Stack Underflow! Cannot pop from the stack\n"); exit(0); } int z=q->r; while (q->f < q->r) { x = dequeue(q); enqueue(&qT, x); } q->f = q->r = 0; qT.r--; while (qT.f != qT.r) { int l = dequeue(&qT); enqueue(q, l); } return z; } int main() { struct queue q; int s; printf("enter the size of queue : "); scanf("%d", &s); q.size = s; q.f = q.r = 0; q.arr = (int *)malloc(q.size * sizeof(int)); printf("queue has been created successfully\n"); push(&q, 1); push(&q, 2); push(&q, 3); printf("poped element is : %d\n", pop(&q)); printf("poped element is : %d\n", pop(&q)); printf("poped element is : %d\n", pop(&q)); return 0; }