模拟栈和模拟队列

栈是一种数据结构,先进后出,只支持一端进行插入和弹出操作,可以用数组进行模拟实现,现在编程语言中都进行了封装,可以直接调用

插入:插入时就是栈顶指针指向的内存区域存放当前要插入的元素,然后栈顶指针自增即可

弹出:弹出就是栈顶指针自减,原来栈顶元素溢出相当于弹出

查询栈顶是否为空:栈为空时即栈顶指针为0

输出栈顶元素:先判断栈是否为空,不为空的话输出栈顶指针减一指向的元素的值就是栈顶元素

题目链接

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N = 100010;
int m;
int stk[N], tt;
int main()
{
    scanf("%d", &m);
    while (m --)
    {
        string op;
        cin >> op;
        int x;
        if(op == "push")
        {
            cin >> x;
            stk[++ tt] = x;
        }
        else if(op == "pop") tt --;
        else if(op == "empty")
        {
            if(tt == 0) cout << "YES" << endl;
            else cout <<"NO" << endl;
        }
        else cout << stk[tt] << endl;
    }
    return 0;
}

队列也是一种数据结构和栈不同的是,它是先进先出,支持在两端进行操作。有一端只能插入数据的叫做队尾,另一端只支持删除数据操作的叫做队头,同样的队列也支持如下几种操作

例题链接

插入:队尾指针指向的内存区域放入要插入的元素,然后队尾指针再自增

弹出:队头指针自增,原来队头指向的内存区域相当于在队列区域的外面,即被弹出

判断队列是否为空:队头指针加一是否等于队尾指针,如果等于则队列为空,否则队列不空

输出队头元素:在队列不空的情况下,输出队头指针加一指向的内存区域中存放的数据即可

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N = 100010;
int m;
int q[N], tt = -1, hh;
int main()
{
    scanf("%d", &m);
    while (m --)
    {
        string op;
        cin >> op;
        int x;
        if(op == "push")
        {
            cin >> x;
            q[++ tt] = x;
        }
        else if(op == "pop") hh ++;
        else if(op == "empty")
        {
            if(tt >= hh) cout << "NO" << endl;
            else cout <<"YES" << endl;
        }
        else cout << q[hh] << endl;
    }
    return 0;
}
posted @ 2022-07-11 20:55  LYL233  阅读(25)  评论(0)    收藏  举报