剑指Offer - 用两个栈实现队列 (C/C++, Java, Pythpn 2.x 实现)

题目描述

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

思路:“进出队列”时两个栈的元素全部“倒腾”一下也行的通,但是效率会很低。

            一个较好的思路就是:一个负责压栈,一个负责弹栈。当弹栈的那个栈空时,再把压栈的那个栈里的元素全部压到弹栈的那个栈里!!!


C/C++:    运行时间:2ms    占用内存:480k

效率较低的方法:每次“进队出队”都会倒腾全部元素!!

class Solution
{
public:
    void push(int node)
    {
        while(!stack2.empty())    //将stack2里的元素全部倒腾到stack1中
        {
            int mid = stack2.top();
            stack2.pop();
            stack1.push(mid);
        }
        stack1.push(node);
    }

    int pop()
    {
        while(!stack1.empty())    //将stack1里的元素全部倒腾到stack2中
        {
            int mid = stack1.top();
            stack1.pop();
            stack2.push(mid);
        }
        int key = stack2.top();
        stack2.pop();
        return key;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

效率较高的方法:stack1:负责压栈,stack2负责弹栈(如果为空,则将stack1中元素压入stack2)

运行时间:4ms    占用内存:480k

class Solution
{
public:
    void push(int node)
    {
        stack1.push(node);
    }

    int pop()
    {
        if(stack2.empty())    //如果stack2为空的话
        {
            while(!stack1.empty())    //则将stack1的元素全部出栈,并压如stack2栈
            {
                int mid = stack1.top();
                stack1.pop();
                stack2.push(mid);
            }
        }
        int key = stack2.top();
        stack2.pop();
        return key;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

Java       运行时间:17ms    占用内存:9288k

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node)
    {
        stack1.push(node);
    }
    
    public int pop()
    {
        if(stack2.empty())
            while(!stack1.empty())
                stack2.push(stack1.pop());
        return stack2.pop();
    }
}

Python 2.x

class Solution:  
    def __init__(self):  
        self.stack1 = []  
        self.stack2 = []  
    def push(self, node):  
        # write code here  
        self.stack1.append(node)  
    def pop(self):  
        # return xx  
        if not self.stack2:      #如果stack2为空的话
            while self.stack1:   #并且 如果stack1不为空
                self.stack2.append(self.stack1.pop())  #则把stack1中的元素 导入到 stack2中
        return self.stack2.pop()  

python里是没有栈和队列的,不过均可以用list,tuple来实现栈和队列

实现栈如下链接:

https://blog.csdn.net/your_answer/article/details/79338498

猜你喜欢

转载自blog.csdn.net/m0_38024592/article/details/80461867