LeetCode225—Implement Stack using Queues

浅浅的花香味﹌ 2022-07-12 09:55 224阅读 0赞

原题链接

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).

分析

要让队首的元素到对尾去,因为stack是先进后出,没次入队之后将队首元素再入队。

  1. class MyStack {
  2. queue<int>q;
  3. public:
  4. /** Initialize your data structure here. */
  5. MyStack() {
  6. }
  7. /** Push element x onto stack. */
  8. void push(int x) {
  9. q.push(x);
  10. for(int i=0;i<q.size()-1;++i)
  11. {
  12. q.push(q.front());
  13. q.pop();
  14. }
  15. }
  16. /** Removes the element on top of the stack and returns that element. */
  17. int pop() {
  18. int v=q.front();
  19. q.pop();
  20. return v;
  21. }
  22. /** Get the top element. */
  23. int top() {
  24. return q.front();
  25. }
  26. /** Returns whether the stack is empty. */
  27. bool empty() {
  28. return q.empty();
  29. }
  30. };

发表评论

表情:
评论列表 (有 0 条评论,224人围观)

还没有评论,来说两句吧...

相关阅读