《剑指offer》用两个栈实现队列

╰+攻爆jí腚メ 2021-10-29 15:32 449阅读 0赞

本题来自《剑指offer》 用两个栈实现队列

题目:

  用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:

  队列定义:先进先出

  栈定义:先进后出

  要实现入队操作:直接在栈1中入栈,将元素压入到栈1中。

  要实现出队操作:

    如果栈2中没有元素则将栈1的全部数据压入栈2;

    如果栈2中有元素,则直接返回栈顶元素即可。

C++ Code:

  1. class Solution
  2. {
  3. public:
  4. void push(int node) {
  5. stack1.push(node); //入队是直接压入栈1中
  6. }
  7. int pop() {
  8. if (stack2.size()<=0){ //如果栈2中没有值
  9. while(stack1.size()>0){ //则将栈1的值全部压入栈2中
  10. int val = stack1.top();
  11. stack1.pop();
  12. stack2.push(val);
  13. }
  14. }
  15. int head = stack2.top(); //取栈2的栈顶,即为出队
  16. stack2.pop(); //栈2顶出栈
  17. return head;
  18. }
  19. private:
  20. stack<int> stack1;
  21. stack<int> stack2;
  22. };

Python Code:

  1. class MyQueue(object):
  2. def __init__(self):
  3. """
  4. Initialize your data structure here.
  5. """
  6. self.stack1 =[] #第一个栈进行队列的输入操作
  7. self.stack2 = [] #第二个栈进行队列的出栈和查看操作
  8. def push(self, x):
  9. """
  10. Push element x to the back of queue.
  11. :type x: int
  12. :rtype: None
  13. """
  14. self.stack1.append(x) #进行入队操作,将元素先在第一个栈中缓存
  15. def pop(self):
  16. """
  17. Removes the element from in front of queue and returns that element.
  18. :rtype: int
  19. """
  20. if not self.stack2: #如果第二个栈是空的
  21. while self.stack1: #循环遍历第一个栈
  22. self.stack2.append(self.stack1.pop())#将第一个栈中的元素全部加入到第二个栈中
  23. return self.stack2.pop() #出栈最后一个元素
  24. def peek(self):
  25. """
  26. Get the front element.
  27. :rtype: int
  28. """
  29. if not self.stack2: #如果第二个栈是空的
  30. while self.stack1: #将第一个占中的所有元素全部加载到第二个栈中
  31. self.stack2.append(self.stack1.pop())
  32. return self.stack2[-1] #返回最后一个元素的值
  33. def empty(self):
  34. """
  35. Returns whether the queue is empty.
  36. :rtype: bool
  37. """
  38. if not self.stack1 and not self.stack2:#只有当两个栈同时(and)空时候,队列为空
  39. return True
  40. else:
  41. return False #否则队列中还有值
  42. # Your MyQueue object will be instantiated and called as such:
  43. # obj = MyQueue()
  44. # obj.push(x)
  45. # param_2 = obj.pop()
  46. # param_3 = obj.peek()
  47. # param_4 = obj.empty()

思考:

  我思故我在。

转载于:https://www.cnblogs.com/missidiot/p/10757487.html

发表评论

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

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

相关阅读