Monday, June 21, 2021
Home coding Write a program to implement queue using stack

Write a program to implement queue using stack

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

queue has two operation:

1-enqueue operation.(push the element)

2-dequeue operation.(pop the element)

Logic:

STEP 1: making push operation costly.
STEP 2:push all first stack element to second stack element  .
STEP 3:push everything back to first stack.

Code

void enQueueOperation(int data) 
{ 
	    	stack<int> stack1, stack2; 
		while (!stack1.empty())
		{ 
			stack2.push(stack1.top()); 
			stack1.pop(); 
		} 
		stack1.push(data); 
		while (!stack2.empty()) 
		{ 
			stack1.push(stack2.top()); 
			stack2.pop(); 
		} 
	} 

	int deQueueOperation() 
	{ 
		if (stack11.empty()) 
		{ 
		cout<<"empty"<<endl;
		} 
		int data = stack1.top(); 
		stack1.pop(); 
		return data; 
	} 

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