LeetCode232—Implement Queue using Stacks

╰半橙微兮° 2022-07-15 02:52 232阅读 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.
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).

分析

栈是后进先出,队列是先进先出。

如果用栈实现队列的话,需要用到两个栈

假设两个栈stack1和stack2,假设现在一组数据压栈,那么他们出栈的顺序肯定是相反的,也就是所谓的后进先出。现在我们将数据压入stack1然后出栈的时候再把数据压入stack2,那么原先stack1中的栈底元素就成了stack2的栈顶元素,弹出的时候也就“先出了”,这就用两个栈实现了一个队列。

代码

  1. class Queue {
  2. private:
  3. stack<int>s1;
  4. stack<int>s2;
  5. public:
  6. // Push element x to the back of queue.
  7. void push(int x) {
  8. s1.push(x);
  9. }
  10. // Removes the element from in front of queue.
  11. void pop(void) {
  12. while(!s1.empty())
  13. {
  14. s2.push(s1.top());
  15. s1.pop();
  16. }
  17. s2.pop();
  18. while(!s2.empty())
  19. {
  20. s1.push(s2.top());
  21. s2.pop();
  22. }
  23. }
  24. // Get the front element.
  25. int peek(void) {
  26. while(!s1.empty())
  27. {
  28. s2.push(s1.top());
  29. s1.pop();
  30. }
  31. int t = s2.top();
  32. while(!s2.empty())
  33. {
  34. s1.push(s2.top());
  35. s2.pop();
  36. }
  37. return t;
  38. }
  39. // Return whether the queue is empty.
  40. bool empty(void) {
  41. return s1.empty();
  42. }
  43. };

说明:这里我愚了。
入队的时候都往s1中压栈,但是出队的时候,需要将s1中所有元素压入s2中,在弹出栈顶元素。我当时害怕逻辑乱了,我又将s2中的所有元素再压回s1中,保持原来的状态。这样做效率非常低,因为每次出队都有O(n)的复杂度

事实上是不必的,当我们出队时,只有当s2栈空时,我们才需要再次将s1中的所有元素压入s2,否则直接让s2弹栈即可
参考:https://discuss.leetcode.com/topic/61137/my-c-solution-with-comments。

发表评论

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

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

相关阅读