Likou brushing notes: 232. Use the stack to realize the queue (only the basic operation of the stack is used, it is easy to understand)

topic:

232. Use a stack to implement a queue

Please use only two stacks to implement a first-in first-out queue. The queue should support all operations supported by the general queue (push, pop, peek, empty):

Implement the MyQueue class:

void push(int x) Push element x to the end of the queue
int pop() Remove from the beginning of the queue and return the element
int peek() Return the element at the beginning of the queue
boolean empty() If the queue is empty, return true; otherwise, Return false

Description:

You can only use standard stack operations-that is, only push to top, peek/pop from top, size, and is empty operations are legal.
The language you are using may not support stacks. You can use list or deque (double-ended queue) to simulate a stack, as long as it is a standard stack operation.

Advanced:

Can you implement a queue with O(1) amortized time for each operation? In other words, the total time complexity of performing n operations is O(n), even if one of the operations may take a long time.

Example:

输入:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

prompt:

1 <= x <= 9
Call push, pop, peek and empty up to 100 times,
assuming that all operations are valid (for example, an empty queue will not call pop or peek operations)

Problem solution ideas:

The queue is a first-in-first-out (FIFO) data structure. The elements in the queue are pushed into the queue from the rear (rear) and popped from the front (front).

The stack is a last-in-first-out (LIFO) data structure. Elements in the stack are pushed from the top of the stack (push) and popped from the top of the stack (pop).

In order to meet the FIFO characteristics of the queue, we need to use two stacks, one of them is used to reverse the order of the elements into the queue, and the other is used to store the final order of the elements.

Join the team (push)

A queue is FIFO, but a stack is LIFO. This means that the newly pushed element must be placed at the bottom of the stack. To achieve this, we first need to move all the elements in s1 to s2, and then push the new elements into s1. Finally, all the elements in s2 are popped, and then the popped elements are pressed into s1.
Insert picture description here

Pop

Just pop directly from s1, because the top element of s1 is the head element of the queue. At the same time, we assign the top element of s1 after popping to the front variable representing the top element of the team.
Insert picture description here

Problem solution python code:

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.A = []
        self.B = []
        self.front = None


    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        while self.A:
            self.B.append(self.A.pop())
        self.A.append(x)
        while self.B:
            self.A.append(self.B.pop())
        self.front = self.A[-1]


    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        t = self.A.pop()
        if self.A: self.front = self.A[-1]
        else: self.front = None
        return t
        


    def peek(self) -> int:
        """
        Get the front element.
        """
        return self.front


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        return not self.A 

# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

Insert picture description here

Author: a-qing-ge
Links: https://leetcode-cn.com/problems/implement-queue-using-stacks/solution/guan-fang-ti-jie-fang-fa-yi-pythonban-by-95l6 /
Source: LeetCode https://leetcode-cn.com/problems/implement-queue-using-stacks/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114382544