Friday, June 18, 2021
Home coding Write a program to implement stack using queue.

Write a program to implement stack using queue.

Given a queue ,we have to write a program to implement stack using queue.

Stack has two operation:

1-push operation.(push the element)

2-pop operation.(pop the element)

Logic:

STEP 1: making push operation costly.
STEP 2:push all first queue element to second queue  .
STEP 3:swap both queue.

Code

void push(int x) 
	{ 
	q2.push(x); 
	while (!q1.empty())
 { 
	q2.push(q1.front()); 
       q1.pop(); 
} 
	swap(q1,q2);
	} 

 void pop() 
    {  
       if (q1.empty())
        {
            return; 
        }
        q1.pop(); 
        
    } 

Ouput:

pushed
popped

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments