NEFU 栈

基本知识

1、栈的基本性质是先进后出,且只能由栈顶输出。

栈的基本操作

1、初始化栈:stack<数据类型 /如int、char或结构体名/ >vis /栈名/
2、入栈:vis.push(x)
3、出栈:vis.pop()
4、判断是否为空:vis.empty() /为空返回值为1/
5、判断栈中元素的数量:vis.size()
6、得到栈顶元素:vis.top()

例题

栈-程序员输入问题

#include <bits/stdc++.h>
using namespace std;
int main()
{
    stack<char>vis;
    stack<char>vis1;
    char x[110],y[110],n=0;
    gets(x);  //字符串的输入带空格
    int m=strlen(x);
    for(int i=0; i<m; i++)
    {
        if(x[i]=='@')
        {
            while(vis.empty()!=1) //判断字符串是否为空
                vis.pop();
            continue;
        }
        if(x[i]=='#')
        {
            if(vis.empty()!=1)
            {
                vis.pop();
                continue;
            }
        }
        vis.push(x[i]);
    }
    while(vis.empty()!=1) //一下部分为将栈按顺序输出!!!!
    {
        vis1.push(vis.top());
        vis.pop();
    }
    while(vis1.empty()!=1)
    {
        printf("%c",vis1.top());
        vis1.pop();
    }
    printf("\n");
    return 0;
}

栈-溶液模拟器

#include <bits/stdc++.h>
using namespace std;
struct vc
{
    int v;
    double c;
};
stack<vc>vis;
int main()
{
    int VO;
    double CO;
    cin>>VO>>CO;
    vis.push({VO,CO});
    int n;
    cin>>n;
    while(n--)
    {
        char pz;
        cin>>pz;
        if(pz=='P')
        {
            int v1,v2,resv;
            double c1,c2,resc;
            cin>>v1>>c1;
            struct vc tmp=vis.top();
            v2=tmp.v;
            c2=tmp.c;
            resv=v1+v2;
            resc=(v1*c1+v2*c2)/resv;
            printf("%d %.5lf\n",resv,resc);
            vis.push({resv,resc});
        }
        if(pz=='Z')
        {
            if(vis.size()==1)
                printf("%d %.5lf\n",VO,CO);
            else
            {
                vis.pop();
                struct vc tmp=vis.top();
                printf("%d %.5lf\n",tmp.v,tmp.c);
            }
        }
    }
    return 0;
}

发布了13 篇原创文章 · 获赞 0 · 访问量 398

猜你喜欢

转载自blog.csdn.net/qq_46126537/article/details/103896272