用数组模拟栈,队列

1.

实现一个栈,栈初始为空,支持四种操作:

  1. push x – 向栈顶插入一个数 x;
  2. pop – 从栈顶弹出一个数;
  3. empty – 判断栈是否为空;
  4. query – 查询栈顶元素。
#include<iostream>
using namespace std;
const int N=100010;
int a[N];
int main()
{
  int M;int tt=-1;
  cin>>M;
  while(M--)
  {
    string s;
    cin>>s;
    if(s=="push")
    {
      int x;cin>>x;
      a[++tt]=x;
    }
    else if(s=="pop")
    {
      tt--;
    }
    else if(s=="empty")
    {
      if(tt==-1)cout<<"YES"<<endl;
      else cout<<"NO"<<endl;
    }
    else 
    {
      cout<<a[tt]<<endl;
    }
  }
  return 0 ;
}

2.

实现一个队列,队列初始为空,支持四种操作:

  1. push x – 向栈顶插入一个数 x;
  2. pop – 从栈顶弹出一个数;
  3. empty – 判断栈是否为空;
  4. query – 查询栈顶元素。
#include<iostream>
using namespace std;
const int N=1000010;
int a[N];
int main()
{
  int M;
  cin>>M;
  int hh=0,tt=-1;
  while(M--)
  {
    string s;
    cin>>s;
    if(s=="push")
    {
      int x;cin>>x;
      a[++tt]=x;
    }
    else if(s=="pop")
    {
      hh++;
    }
    else if(s=="empty")
    {
      if(tt-hh>=0)cout<<"NO"<<endl;
      else cout<<"YES"<<endl;
    }
    else 
    {
      cout<<a[hh]<<endl;
    }
  }
  return 0 ;
}

 

 

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值