Python data structure -----leetcode implements stack with queue

Table of contents

Foreword:

 Method steps

example

Python code implementation

225. Implement a stack with a queue


Foreword:

        In the last issue, I learned how to implement the queue through two stacks. In this issue, I will also talk about how to implement the function of the stack through two queues. Let’s learn together. (The previous issue linked to the Python data structure ----- leetcode232. Implementing a queue with a stack_Grey Le Tad's Blog-CSDN Blog )

 Method steps

        Similarly, two empty queues must be prepared first, namely queue_in and queue_tem. The first one is used as a queue for data storage, and the second one is used as a queue for temporary storage of data. If you want to push into the stack, just put the data into queue_in directly. If you want to get out of the stack, first judge whether the data in the entire stack is empty. In the queue-tem, when there is only the last data left in the queue_in, the data will be dequeued, and then the stack operation will be realized.

example

1. Push operation: directly enqueue the data a, b, c, and d into queue_in in sequence  

 2. Pop-up operation: first dequeue the data in queue_in one by one and put them into queue_tem for temporary storage, and then wait until the last data d is left in queue_in. At this time, it is enough to dequeue and return this data.

 3. After the queue is completed, put the data in queue_tem back into queue_in to ensure that queue_in is not empty

 The above process basically realizes the operation of two queues to realize the stack

Python code implementation

class MyQueue(object):
    def __init__(self):
        '''初始化两个空栈'''
        self.__stack_in = []
        self.__stack_out = []

    def isempty(self):
        '''判断队列是否为空'''
        if not self.__stack_in and not self.__stack_out:
            return True
        return False

    def inqueue(self, data):
        '''入队'''
        self.__stack_in.append(data)

    def dequeue(self):
        '''出队'''
        if self.__stack_out:  # 判断栈stack_out是否空
            return self.__stack_out.pop()
        else:
            if not self.__stack_in:
                return -1  # 如果都队列为空的话就返回-1
            else:
                while self.__stack_in:
                    self.__stack_out.append(self.__stack_in.pop())
            return self.__stack_out.pop()

    def showqueue(self):
        return self.__stack_out[::-1] + self.__stack_in

225. Implement a stack with a queue

 Please use only two queues to implement a last-in-first-out (LIFO) stack, and support all four operations (push, top, pop, and empty) of a normal stack.

Implement the MyStack class:

void push(int x) pushes the element x onto the top of the stack.
int pop() removes and returns the top element of the stack.
int top() Returns the top element of the stack.
boolean empty() Returns true if the stack is empty; otherwise, returns false.
 

Notice:

You can only use the basic operations of the queue - namely push to back, peek/pop from front, size and is empty.
Your language may not support queues. You can use list (list) or deque (double-ended queue) to simulate a queue, as long as it is a standard queue operation.

Example:

输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

Explanation:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // returns 2
myStack.pop(); // returns 2
myStack.empty(); // return False

class MyStack:

    def __init__(self):
        self.queue1 = []
        self.queue2 = []

    def push(self, x: int) -> None:
        self.queue1.append(x)

    def pop(self) -> int:
        if not self.queue1:
            return -1
        else:
            while not len(self.queue1) == 1:
                self.queue2.append(self.queue1.pop(0))
            res = self.queue1.pop()
            while self.queue2:
                self.queue1.append(self.queue2.pop(0))
            return res

    def top(self) -> int:
        return self.queue1[len(self.queue1) - 1]

        return self.queue1[0]

    def empty(self) -> bool:
        return self.queue1 == []

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

Well, that's all for today, see you in the next issue!

Share a wallpaper: 

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/130176145