225. Implement Stack using Queues

待我称王封你为后i 2023-07-03 07:07 95阅读 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.

Example:

  1. MyStack stack = new MyStack();
  2. stack.push(1);
  3. stack.push(2);
  4. stack.top(); // returns 2
  5. stack.pop(); // returns 2
  6. stack.empty(); // returns false

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. class MyStack {
  2. public:
  3. /** Initialize your data structure here. */
  4. MyStack() {
  5. }
  6. /** Push element x onto stack. */
  7. void push(int x) {
  8. _data.push(x);
  9. for(int i = 0;i< _data.size() -1;i++)
  10. {
  11. int val = _data.front();
  12. _data.pop();
  13. _data.push(val);
  14. }
  15. }
  16. /** Removes the element on top of the stack and returns that element. */
  17. int pop() {
  18. int val = _data.front();
  19. _data.pop();
  20. return val;
  21. }
  22. /** Get the top element. */
  23. int top() {
  24. return _data.front();
  25. }
  26. /** Returns whether the stack is empty. */
  27. bool empty() {
  28. return _data.empty();
  29. }
  30. queue<int> _data;
  31. };
  32. /**
  33. * Your MyStack object will be instantiated and called as such:
  34. * MyStack* obj = new MyStack();
  35. * obj->push(x);
  36. * int param_2 = obj->pop();
  37. * int param_3 = obj->top();
  38. * bool param_4 = obj->empty();
  39. */

发表评论

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

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

相关阅读