232. Implement Queue using Stacks

刺骨的言语ヽ痛彻心扉 2023-07-03 07:06 109阅读 0赞

Implement the following operations of a queue using stacks.

  • push(x) — Push element x to the back of queue.
  • pop() — Removes the element from in front of queue.
  • peek() — Get the front element.
  • empty() — Return whether the queue is empty.

Example:

  1. MyQueue queue = new MyQueue();
  2. queue.push(1);
  3. queue.push(2);
  4. queue.peek(); // returns 1
  5. queue.pop(); // returns 1
  6. queue.empty(); // returns false

Notes:

  • You must use only standard operations of a stack — which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

题意:用栈(先进后出)实现队列(先进先出)。

  1. class MyQueue {
  2. public:
  3. /** Initialize your data structure here. */
  4. MyQueue() {
  5. }
  6. /** Push element x to the back of queue. */
  7. void push(int x) {
  8. _input.push(x);
  9. }
  10. /** Removes the element from in front of queue and returns that element. */
  11. int pop() {
  12. if(_output.empty())
  13. {
  14. while(!_input.empty())
  15. {
  16. _output.push(_input.top());
  17. _input.pop();
  18. }
  19. }
  20. int temp = _output.top();
  21. _output.pop();
  22. return temp;
  23. }
  24. /** Get the front element. */
  25. int peek() {
  26. if(_output.empty())
  27. {
  28. while(!_input.empty())
  29. {
  30. _output.push(_input.top());
  31. _input.pop();
  32. }
  33. }
  34. return _output.top();
  35. }
  36. /** Returns whether the queue is empty. */
  37. bool empty() {
  38. return _input.empty() && _output.empty();
  39. }
  40. private:
  41. stack<int> _input;
  42. stack<int> _output;
  43. };
  44. /**
  45. * Your MyQueue object will be instantiated and called as such:
  46. * MyQueue* obj = new MyQueue();
  47. * obj->push(x);
  48. * int param_2 = obj->pop();
  49. * int param_3 = obj->peek();
  50. * bool param_4 = obj->empty();
  51. */

发表评论

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

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

相关阅读