栈与队列

泄露秘密 提交于 2020-03-02 16:24:05

栈的数组实现

  1. 确定好栈底的元素
  2. 边界条件
  3. 变化过程

栈底是-1

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 10;
int tt;
int stk[maxn];

void init()
{
    tt = 0;
    // tt = 0的时候为空,因为如果不为空的话他肯定不会在0的位置
}

void push(int x)
{
    stq[tt++] = x;
}

void pop()
{
    if(tt > 0) tt--;
}

int query()
{
    return stq[tt - 1];
}

bool empty()
{
    return tt > 0 ? false : true;
}
void read()
{
    int x;
    string op;
    cin >> op;
    if(op == "push")
    {
        cin >> x;
        push(x);
    }
    else if(op == "query")
    {
        cout << query() << endl;
    }
    else if(op == "pop")
    {
        pop();
    }
    else
    {
        if(empty()) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
}
int main()
{
    int m;
    cin >> m;
    while (m -- )
    {
        read();
    }
    return 0;
}

栈底是0

#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;
}

队列的数组实现

队尾是0

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 10;
int tt, kk;
int stq[maxn];

void init()
{
    tt = 0;
    kk = 0;
}

void push(int x)
{
    stq[kk++] = x;
}

void pop()
{
    if(tt < kk) tt++;
    else printf("-1");
}

int query()
{
    return stq[tt];
}

bool empty()
{
    return tt == kk ? false : true;
}

void read()
{
    int x;
    string op;
    cin >> op;
    if(op == "push")
    {
        cin >> x;
        push(x);
    }
    else if(op == "query")
    {
        cout << query() << endl;
    }
    else if(op == "pop")
    {
        pop();
    }
    else
    {
        if(empty()) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
}
int main()
{
    int m;
    init();
    cin >> m;
    while (m -- )
    {
        read();
    }
    return 0;
}

队尾是-1

#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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!