两个栈实现队列

(By making enQueue operation costly) This method makes sure that oldest entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used.

enQueue(q, x)

  1. While stack1 is not empty, push everything from stack1 to stack2.
  2. Push x to stack1 (assuming size of stacks is unlimited).
  3. Push everything back to stack1.
    Here time complexity will be O(n)

deQueue(q)

  1. If stack1 is empty then error
  2. Pop an item from stack1 and return it
    Here time complexity will be O(1)
// CPP program to implement Queue using 
// two stacks with costly enQueue() 
#include <bits/stdc++.h> 
using namespace std; 

struct Queue { 
	stack<int> s1, s2; 

	void enQueue(int x) 
	{ 
		// Move all elements from s1 to s2 
		while (!s1.empty()) { 
			s2.push(s1.top()); 
			s1.pop(); 
		} 

		// Push item into s1 
		s1.push(x); 

		// Push everything back to s1 
		while (!s2.empty()) { 
			s1.push(s2.top()); 
			s2.pop(); 
		} 
	} 

	// Dequeue an item from the queue 
	int deQueue() 
	{ 
		// if first stack is empty 
		if (s1.empty()) { 
			cout << "Q is Empty"; 
			exit(0); 
		} 

		// Return top of s1 
		int x = s1.top(); 
		s1.pop(); 
		return x; 
	} 
}; 

// Driver code 
int main() 
{ 
	Queue q; 
	q.enQueue(1); 
	q.enQueue(2); 
	q.enQueue(3); 

	cout << q.deQueue() << '\n'; 
	cout << q.deQueue() << '\n'; 
	cout << q.deQueue() << '\n'; 

	return 0; 
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值