Chapter 3 | Stacks and Queues

stack 、queue、priority_queue(stl)

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
stack<int>s;

void _stack(){
    for(int i = 0 ; i <= 4; i++)
        s.push(i);
    cout <<s.top()<<endl;
    s.emplace(233);//对于在容器中添加类的对象时, 相比于push_back,emplace_back可以避免额外类的复制和移动操作.
    cout <<s.top()<<endl;

}
void _queue(){
    queue<int>q;
    q.push(1);
    if(!q.empty()){
        cout << q.front() <<endl;
        q.pop();
    }
}
void p_q(){
    priority_queue<int> bigtosmall;
    priority_queue<int,vector<int>,greater<int> >smalltobig;
    for(int i = 1; i <= 10 ; i++){
        bigtosmall.push(i);
        smalltobig.push(i);
    }
    while(!bigtosmall.empty()){
        cout << bigtosmall.top() <<"   ";

        bigtosmall.pop();
    }
    cout <<endl;
    while(!smalltobig.empty()){
        cout << smalltobig.top() <<"   ";
        smalltobig.pop();
    }
    cout <<endl;
}
int main(){
    _stack();
    _queue();
    p_q();
}

单调栈

实现一个栈,除了push和pop操作,还要实现min函数以返回栈中的最小值。 push,pop和min函数的时间复杂度都为O(1)。

维护一个单调递减的栈,所栈首就是当前的最小值,pop的时候如果单调栈首的序号是这个,那也要pop这个单调栈,数值可能重复,所以单调栈维护的是同一个值的最小序号。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,887评论 1 32
  • 1.设计模式是什么? 你知道哪些设计模式,并简要叙述?设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型...
    龍飝阅读 6,632评论 0 12
  • 作者:同梦奇缘链接:https://segmentfault.com/a/1190000017905515 一、认...
    grain先森阅读 14,850评论 0 14
  • 昨天由于春节临近,家家都在做卫生,我也不另外,白天在店里边干活边做卫生,晚上8:30回婆婆住的地方,我也在想完成功...
    王泽华wzh阅读 1,135评论 0 0
  • 梦想在什么地方 总是那么令人向往 我不顾一切走在路上 就是为了来到你的身旁 梦想,有多大多远,它在哪里 远方,长路...
    浩宇小丸子阅读 2,773评论 2 4

友情链接更多精彩内容