第八章:数组模拟栈和队列

一、数组模拟栈

1、逻辑结构:

请添加图片描述

2、物理结构:

请添加图片描述

3、接口函数:

(1)提前准备:

const int N=100010;
int stk[N],top;

(2)初始化:

void init()
{
	top=0;
}

(3)插入:

void insert(int k)
{
	stk[++top]=k;
}

我们这里默认stk[0]处不存储数据,这样当top等于0的时候,说明栈为空,而0恰好是假的意思,所以这样写便于判断栈是否为空。

(4)删除:

void remove()
{
	top--;
}

(5)访问栈顶:

int top()
{
	return stk[top];
}

(6)判断是否为空:

bool empty()
{
	if(top)return false;
	else return true;
}

4、例题:

在这里插入图片描述

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

二、数组模拟队列

1、逻辑结构:

请添加图片描述

2、物理结构:

请添加图片描述

3、接口函数:

(1)前期准备

const int N=100010;
int q[N],hh,tt;

(2)初始化

void init()
{
	tt=-1;
	hh=0;
}

(3)插入

void insert(int x)
{
	q[++tt]=x;
}

(4)删除

void remove()
{
	hh++;
}

(5)查看队尾

int back()
{
	return q[tt];
}

(6)查看队头

int front()
{
	return q[hh];
}

(7)判断是否为空

bool empty()
{
	if(hh<=tt)return false;
	else true;
}

4、例题:

在这里插入图片描述

#include<iostream>
using namespace std;

const int N=100010;
int m;
int q[N],head,tail=-1;

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

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值