http://blog.csdn.net/hanjing_1995/article/details/51539578
使用两个栈实现一个队列
思路一:
我们设定s1是入栈的,s2是出栈的。
入队列,直接压到s1即可
出队列,先把s1中的元素倒入到s2中,弹出s2中的栈顶元素;再把s2的剩余元素全部倒回s1中。
缺点:
每次只要出栈一个元素就要将元素倒来倒去,麻烦!!!
思路2:
入队列时:
如果s1为空,把s2中所有的元素倒出压到s1中。否则直接压入s1
出队列时:
如果s2不为空,把s2中的栈顶元素直接弹出。否则,把s1的所有元素全部弹出压入s2中,再弹出s2的栈顶元素
思路1无条件地每次都要将元素倒来倒去,思路2出队时较思路1简单
思路3:
我们设定s1是入栈的,s2是出栈的
入队列:直接压入元素至s1即可
出队列:如果s2不为空,把s2中的栈顶元素直接弹出。否则,把s1的所有元素全部弹出压入s2中,再弹出s2的栈顶元素
相比于方法2,入队直接压入即可~
那么,我们可以看出,思路三最简单,我们下面看下代码。
代码实现:
1)我们直接调用库里的stack来实现。(一般调用库里的就行了)
2)自己实现栈实现。
(1个细节):
注意再将元素倒入另一个栈时,代码并不是先pop,再push。因为这样push后元素就找不到了。因此要先访问到栈顶元素top,再push,而后pop。
本文出自 “Han Jing's Blog” 博客,请务必保留此出处http://10740184.blog.51cto.com/10730184/1763006