Implementation of Queues using Stack in C
How to implement Queue using Stack?
Implementation of Queues using Stack in C is a process of creating a queue using Stacks. In this article, we will be using a single stack for the purpose. When a single stack is used for implementing queues recursive stack call used. This article contains in detail steps and algorithm for all the functions of queue i.e to insert data,
to delete data and to print the data.
Queue Using Stack in C
enqueue(data)
- In this enqueue function recursively call push() function.
- In this push function check if the stack is full or not
- If the stack is we cannot add more elements.
- Else add the element at top of stack and increase the value of top by 1.
dequeue()
- In this function first we will check if the queue has some element or not.
- If our queue is empty then we cannot delete any element from it.
- Else if there is only one element in the queue we will pop an element from the top of stack.
- Else we will pop all the data from the stack until top reaches to zero and will push back the removed data after poping the element at top=0.
print()
- Initialize a for loop from zero till the top.
- Print the element at every successful iteration.
- In this way we can display our queue.
Algorithm for enqueue(int x)
- PUSH(X)
push(x)
- VOID PUSH(INT X)
- IF(TOP == N-1)
- RETURN STACK IS FULL
- ELSETOP++
- S[TOP] = X
Algorithm for dequeue()
- IF(TOP == -1)
- RETURN QUEUE IS EMPTY
- ELSE IF(TOP == 0)
- RETURN POP()
- DATA = POP()
- RES =DEQUEUE()
- PUSH(DATA)
- RETURN RES
pop()
- RETURN S[TOP–]
Algorithm for print()
- FOR I=0 TO TOP
- RETURN S[I]
Code for implementing queue using stack in C
Run
#include<stdio.h> #include<stdlib.h> #define N 20 //defining the size of queue int s[N], top = -1; int pop () //function to remove an element from stack { return s[top--]; } void push (int x) //function to insert an element into stack { if (top == N - 1) printf ("Stack is Full"); else { top++; s[top] = x; } } void enqueue (int x) { push (x); } void display () //function to print elements of a queue { int i; for (i = 0; i <= top; i++) printf (" %d ", s[i]); } int dequeue () { int data, res; if (top == -1) printf ("Queue is Empty"); else if (top == 0) return pop (); data = pop (); res = dequeue (); push (data); return res; } int main () { enqueue (5); enqueue (10); enqueue (15); enqueue (20); enqueue (25); printf ("Queue:"); display (); printf ("\nQueue After Dequeue:"); dequeue (); display (); }
Output
Queue: 5 10 15 20 25 Queue After Dequeue: 10 15 20 25
Login/Signup to comment