1.定义:利用一组地址连续的存储单元依次自栈底到栈顶存放栈的数据元素.
(而栈顶是随着插入和删除而变化的,可以用一个整形变量top存放栈顶的指针,数据入栈或出栈时使整形变量 top分别加1或减1。)
2.栈的基本操作:
(1)初始化栈 stackvis ,定义一个栈
(2)入栈 vis.push(x)
(3)出栈 vis.pop()
(4)判断是否为空 vis.empty()
(5)判断栈中元素的数量vis.size()
(6)得到栈的栈顶元素 vis.top()
综上: #include
用<bits/stdc++.h>则无需考虑头文件.
题目
problem A:栈-程序员输入问题
nefu 1624

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
 int main()
 {
  stack<char>s1;
  stack<char>s2;
   char a[100];
   int i,n;
   gets(a);
   n= strlen(a);
   for(i=0;i<n;i++)
   {
       if(a[i]=='@')
       {
           while(!s1.empty())
               s1.pop();
           continue;
       }
      else if(a[i]=='#')
       {
         if(!s1.empty())
         s1.pop();
         continue;
       }
       else s1.push(a[i]);
   }
   while(!s1.empty())
   {
       s2.push(s1.top());
       s1.pop();
   }
   while(!s2.empty())
   {printf("%c",s2.top());
   s2.pop();}
   printf("\n");
   return 0;
 }

problem B:栈-括号匹配
nefu 1630

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
char a[300];
 int main()
 {
  stack<char>s;
   int i,n;
   scanf("%s",a);
   n=strlen(a);
   for(i=0;i<n;i++)
   {
      if(s.empty())
      s.push(a[i]);
    else
      {
        if(s.top()=='('&&a[i]==')')
            s.pop();
        else if (s.top()=='['&&a[i]==']')
         s.pop();
          else  s.push(a[i]);
      }
   }
    if(s.empty())
        printf("OK\n");
    else
        printf("Wrong\n");

   return 0;
 }

problem C:栈-溶液模拟器
nefu 1627

#include <iostream>
#include <bits/stdc++.h>
#include <algorithm>
#include <stack>
using namespace std;
typedef struct /*rongye*/{
int v;
double c;
}liquid;/*由于有typedef所以liquid在这里不是变量,而是结构体的类型,liquid=struct rongye*/
stack<liquid>vis;
 int main()
 {
   int v0,v1,v2,v3,n;
   double c0,c1,c2,c3;
   string str;/*string简化了定义字符数组的麻烦,直接写str即可*/
   ios::sync_with_stdio(false);
   cin>>v0>>c0>>n;
   vis.push({v0,c0});/*把一组数压入栈内,结构体入栈*/
   while(n--)
   {  cin>>str;
       if(str=="P")/*string输入记得写成”“*/
       {
           liquid tmp=vis.top();
           v1=tmp.v;
           c1=tmp.c;
           cin>>v2>>c2;
           v3=v1+v2;
           c3=(v1*c1+v2*c2)/v3;
           printf("%d %.5lf\n",v3,c3);
           vis.push({v3,c3});/*新数组压入栈*/

       }
       if(str=="Z")
       {
           if(vis.size()==1)
            printf("%d %.5lf\n",v0,c0);
           if(vis.size()>1)
            {vis.pop();
            liquid tmp=vis.top();
           printf("%d %.5lf\n",tmp.v,tmp.c);
            }
       }
   }
   return 0;
 }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值