前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数据结构—栈/队列

数据结构—栈/队列

作者头像
attack
发布2018-04-11 15:07:25
5650
发布2018-04-11 15:07:25
举报

仔细一想

似乎自己已经有半年已经没有手写栈/队列了

STL里面的栈/队列好用是好用但是速度令人堪忧啊。

于是乎今天自己手写了一份栈&&队列,

以后就用这种格式了,跟STL说再见

用的是STL的写法

关于栈和队列,推荐几篇博客

https://www.cnblogs.com/QG-whz/p/5170418.html

http://blog.csdn.net/hguisu/article/details/7674195

http://blog.csdn.net/juanqinyang/article/details/51354293

代码语言:javascript
复制
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 using namespace std;
 6 const int MAXN=1e6+10;
 7 struct stack
 8 {
 9     int now,s[1001];
10     stack(){now=0;memset(s,0,sizeof(s));}
11     void pop(){now--;if(now<0)puts("0");}//弹出
12     int size(){return now;}//元素个数
13     void push(int x){s[++now]=x;}//加入元素
14     int top(){return s[now];}//取栈顶元素
15     bool empty(){return !now>=1;}//判断是否为空
16 };
17 int n,opt,x;
18 int main()
19 {
20     stack s;
21     cin>>n;
22     while(n--)
23     {
24         cin>>opt;
25         if(opt==1)  cin>>x,s.push(x);
26         if(opt==2)  s.pop();
27         if(opt==3)  printf("The size of stack is :%d\n",s.size());
28         if(opt==4)  printf("The top of stack is :%d\n",s.top());
29     }
30     return 0;  
31 }

队列

代码语言:javascript
复制
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int MAXN=1e6+10;
struct queue
{
    int head,tail,q[1001];
    queue(){head=tail=0;memset(q,0,sizeof(q));}
    void pop(){head++;if(head>tail) puts("error");}
    int front(){return q[head];}
    void push(int x){q[tail++]=x;}
    int size(){return tail-head;}
};
int n,opt,x;
int main()
{
    queue q;
    cin>>n;
    while(n--)
    {
        cin>>opt;
        if(opt==1)  cin>>x,q.push(x);
        if(opt==2)  q.pop();
        if(opt==3)  printf("The size of queue is :%d\n",q.size());
        if(opt==4)  printf("The front of queue is :%d\n",q.front());
    }
    return 0;  
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-11-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 队列
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档