Leetcode刷题 232题:用栈实现队列(基于python3和c++两种语言)

Leetcode刷题 232题:用栈实现队列(基于python3和c++两种语言)

题目:

使用栈实现队列的下列操作:

push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

说明:
你只能使用标准的栈操作 – 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

**

解题思路:

利用两个栈的思想去进行解题的,定义一个输入栈和一个输出栈,因为栈是后进先出,而队列是先进先出的,所以要用栈来实现队列的话,是需要用两个栈来实现的,即一个输入栈和一个输出栈的。首先,利用输入栈先存入应该需要存入的元素,当输出栈里面是空的时候,才可以从输入栈中导入数据进入输出栈,这样一来,就把输入栈中的输入顺序在输出栈完全颠倒了,比如,进如输入栈的元素顺序是:1 2 3 4 5,而这些元素进入输出栈的顺序则为:5 4 3 2 1;然后,再讲这些元素依次弹出,则就实现了队列的操作,即先进先出。

**

c++程序:

class MyQueue {
    
    
public:
    stack<int> stIn;   //定义输入栈
    stack<int> stOut;  //定义输出栈
    /** Initialize your data structure here. */
    MyQueue() {
    
    

    }
    /** Push element x to the back of queue. */
    void push(int x) {
    
    
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
    
    
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
    
    
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
    
    
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
    
    
        int res = this->pop(); // 直接使用已有的pop函数(函数复用)
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
    
    
        return stIn.empty() && stOut.empty();
    }
};

结果:
在这里插入图片描述

python3程序:

class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.queue = []
        self.help = []


    def push(self, x: int) -> None:
        """
        Push element x to the back of queue.
        """
        self.queue.append(x)


    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        if len(self.help)==0:
            while(len(self.queue)!=0):
                self.help.append(self.queue.pop())
        return self.help.pop()
        

    def peek(self) -> int:
        """
        Get the front element.
        """
        if len(self.help)==0:
            while(len(self.queue)!=0):
                self.help.append(self.queue.pop())
        return self.help[-1]
        


    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        if len(self.queue)==0 and len(self.help)==0:
            return True
        return False

# 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()


结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39350172/article/details/108869500