[剑指Offer]笔记5.用两个栈实现队列 C++实现

Problem Description

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

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

    int pop() {
    
    }
private:
    stack<int> stack1;
    stack<int> stack2;
};

Mentality

由于作答框架里使用的是stack模板,则在实现函数的时候,应该使用stack模板提供的方法来作答。
用栈来实现队列,需要两个栈。队列的输入和栈的输入一样,直接压入即可。出队操作的实现是从第一个栈全部弹出压入第二个栈,取得第二个栈的栈顶元素之后,再把第二个栈里面剩余的元素返回到第一个栈内。

Other Details

1.stack:栈,一个先进后出的容器。
2.头文件#include < stack >
3.常用函数:
1)void push()
stack.push(x):将x压入栈,时间复杂度为O(1)
2)const reference top()
x=stack.top():获取栈顶元素,时间复杂度为O(1)
3)void pop()
stack.pop():出栈顶元素
4)bool empty()
stack.empty():判断栈是否为空
5)int size()
int count=stack.size():返回栈元素的个数

示例代码如下:

#include<iostream>
#include<stack>
using namespace std;
int main()
{
    stack<int> s;
    if(s.empty()==true)
    	cout<<"Empty";
    for(int i=1;i<=5;i++)
    {
        sk.push(i);//push(i)把i压入栈,入栈顺序为1,2,3,4,5
    }
    cout<<s.size();//5
    for(int i=1;i<=5;i++){
    	cout<<sk.top()<<endl;//top取栈顶元素,出栈顺序为5,4,3,2,1
    	sk.pop();//令栈顶元素出栈
	}
    return 0;
}

Code (C++)

#include<iostream> 
#include<stack>
using namespace std;
class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
        }
        int temp=stack2.top();
        stack2.pop();
        //把stack2里剩下的倒回stack1去 
        while(!stack2.empty()){
            stack1.push(stack2.top());
            stack2.pop();
        }
        return temp;
    }
private:
    stack<int> stack1;
    stack<int> stack2;
};
int main(){
	Solution s;
	s.push(1);
	s.push(2);
	s.push(3);
	cout<<s.pop()<<endl;
	cout<<s.pop()<<endl;
	cout<<s.pop()<<endl;
	s.push(4);
	cout<<s.pop();
	return 0;
}

本地运行结果如下:
在这里插入图片描述
已通过所有的测试用例,欢迎指正批评(´▽`ʃ♡ƪ)

发布了19 篇原创文章 · 获赞 10 · 访问量 1201

猜你喜欢

转载自blog.csdn.net/qq_38655181/article/details/105341920