码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_Implement Stack using Queues

时间:2015-08-07 11:18:42      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:implement stack usin   leetcode   java   

描述:

Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

思路:

1.跟用栈实现队列不同,我感觉用队列去实现栈要困难的多,以至于根本就想不起来,参考了网络上的思路才算是有了写头绪,原来是这个这个样子。。。

2.如果用栈来实现队列还算可以理解的话,但用队列来实现栈就只有两个字来形容:no zuo no die!,下面我就来描述下这种奇葩的思路:

3.用两个队列queue1和queue2来模拟栈,具体怎么模拟呢?queue1是操作队列,先进先出,queue2是中转队列,每次取元素时,将0~size-2个元素先中转到queue2中,然后取出queue1的最后一个元素,然后,对,然后在将queue1中的元素再依次放回queue2中,直至stack2为空且没有新的元素进栈,循环终止

4.好有想法的一个思路,希望还有更简洁明快的思路出现。

代码:



版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode_Implement Stack using Queues

标签:implement stack usin   leetcode   java   

原文地址:http://blog.csdn.net/mnmlist/article/details/47334367

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!