c code for queue using stack.

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

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

    Code

    #include <stdio.h> #include <stdlib.h> struct stack { int size; int top; int *arr; }; int isEmpty(struct stack *ptr) { if (ptr->top == -1) { return 1; } else { return 0; } } int isFull(struct stack *ptr) { if (ptr->top == ptr->size - 1) { return 1; } else { return 0; } } void push(struct stack *ptr, int val) { if (isFull(ptr)) { printf("Stack Overflow! Cannot push %d to the stack\n", val); } else { ptr->top++; ptr->arr[ptr->top] = val; } } int pop(struct stack *ptr) { if (isEmpty(ptr)) { printf("Stack Underflow! Cannot pop from the stack\n"); return -1; } else { int val = ptr->arr[ptr->top]; ptr->top--; return val; } } void enqueue(struct stack *ptr, int x) { push(ptr, x); } int dequeue(struct stack *ptr) { if (isEmpty(ptr)) { printf("Queue is empty"); exit(0); } int x = pop(ptr); if (isEmpty(ptr)){ return x; } int i = dequeue(ptr); push(ptr, x); return i; } int main() { int s; struct stack *sp = (struct stack *)malloc(sizeof(struct stack)); printf("enter the size of queue : "); scanf("%d", &s); sp->size = s; sp->top = -1; sp->arr = (int *)malloc(sp->size * sizeof(int)); printf("Stack has been created successfully\n"); enqueue(sp, 9); enqueue(sp, 99); enqueue(sp, 999); enqueue(sp, 9999); printf("dequeued element is : %d\n", dequeue(sp)); printf("dequeued element is : %d\n", dequeue(sp)); printf("dequeued element is : %d\n", dequeue(sp)); printf("dequeued element is : %d\n", dequeue(sp)); return 0; }