【数据结构】栈和队列算法总结

知识概览

在数据结构中,栈和队列都属于线性表。栈是先进后出(FILO)的,队列是先进先出(FIFO)的。

代码模板

#include <iostream>

using namespace std;

const int N = 100010;

// ********************** 栈
int stk[N], tt;

// 插入
stk[++tt] = x;

// 弹出
tt--;

// 判断栈是否为空
if (tt > 0) not empty
else empty

// 栈顶
stk[tt];

// ********************** 队列

// 在队尾插入元素,在对头弹出元素
int q[N], hh, tt = -1;

// 插入
q[++tt] = x;

// 弹出
hh++;

// 判断队列是否为空
if (hh <= tt) not empty
else empty

// 取出队头元素
q[hh];

题目链接

https://www.acwing.com/problem/content/830/

代码(数组模拟)

#include <iostream>

using namespace std;

const int N = 100010;

int m;
int stk[N], tt;

int main()
{
    cin >> m;
    
    while (m--)
    {
        string op;
        int x;
        
        cin >> op;
        if (op == "push")
        {
            cin >> x;
            stk[++tt] = x;
        }
        else if (op == "pop") tt--;
        else if (op == "empty") cout << (tt ? "NO" : "YES") << endl;
        else cout << stk[tt] << endl;
    }
    
    return 0;
}

代码(STL)

#include <iostream>
#include <stack>

using namespace std;

int m;
stack<int> stk;

int main()
{
    cin >> m;
    
    while (m--)
    {
        int x;
        string op;
        
        cin >> op;
        if (op == "push")
        {
            cin >> x;
            stk.push(x);
        }
        else if (op == "pop") stk.pop();
        else if (op == "empty") cout << (stk.empty() ? "YES" : "NO") << endl;
        else cout << stk.top() << endl;
    }
    
    return 0;
}

队列

题目链接

https://www.acwing.com/problem/content/831/

代码(数组模拟)

#include <iostream>

using namespace std;

const int N = 100010;

int m;
int q[N], hh, tt = -1;

int main()
{
    cin >> m;
    
    while (m--)
    {
        string op;
        int x;
        
        cin >> op;
        if (op == "push")
        {
            cin >> x;
            q[++tt] = x;
        }
        else if (op == "pop") hh++;
        else if (op == "empty") cout << (hh <= tt ? "NO" : "YES") << endl;
        else cout << q[hh] << endl;
    }
    
    return 0;
}

代码(STL)

#include <iostream>
#include <queue>

using namespace std;

int m;
queue<int> q;

int main()
{
    cin >> m;
    
    while (m--)
    {
        int x;
        string op;
        
        cin >> op;
        if (op == "push")
        {
            cin >> x;
            q.push(x);
        }
        else if (op == "pop") q.pop();
        else if (op == "empty") cout << (!q.empty() ? "NO" : "YES") << endl;
        else cout << q.front() << endl;
    }
    
    return 0;
}

参考资料

  1. AcWing算法基础课
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ykycode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值