STL——栈运用(stack)

本文通过一个具体实例详细介绍了栈(stack)的数据结构及其在C++中的使用方法,包括基本操作如push、pop等,并展示了如何利用栈解决实际问题——展开字符串算法。

stack 用法(先进后出):

#include<stack>

stack<int> st;

接口函数:

push() 插入一个元素到栈顶;

top()返回顶层元素;

pop()移除栈顶元素;

size()返回栈中的元素个数;

empty()返回stack是否为空(空返回true,非空返回false);

例题:(hdoj 1274 展开字符串)

思路:

1.如果是左括号,或者数字则直接压入栈中

2.如果是字母

    2.1 判断栈顶是不是数字num,如果是循环num次,把字母压入栈

    2.2 如果不是直接压入栈

3.如果是右括号

    3.1 将括号内的字符存入temp数组中,并把这些字符出栈

        3.1.1 然后看栈顶,如果是数字则循环多次,将temp压入栈中

        3.1.2 如果不是直接压入栈中

4.最后将栈中所有元素存入数组ans,并输出;

代码如下:

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <cmath>
#include <string.h>
#include <stack>
#include<string>
using namespace std;
int is_num(char a)
{
    if (a >= '1'&&a <= '9')
        return 1;
    else
        return 0;
}
int main()
{
    stack <char >a;
    int n;
    char s[1000];
    string temp;
    string ans;

    int len;
    int num;
    int i, j;
    cin >> n;

    while (n--)
    {

        cin >> s;
        ans.clear();
        temp.clear();
        len = strlen(s);
        for (i = 0; i<len; i++)
        {
            if (is_num(s[i]) || s[i] == '(')
                a.push(s[i]);
            else if (s[i] >= 'a'&&s[i] <= 'z')
            {
                if (is_num(a.top()))
                {
                    num = a.top()-'0';
                    a.pop();
                    while (num--)
                        a.push(s[i]);
                }
                else
                    a.push(s[i]);

            }
            else
            {
                while (a.top() != '(')
                {
                    temp.insert(temp.begin(), a.top());
                    a.pop();
                }
                a.pop();
                if (is_num(a.top()))
                {
                    num = a.top() - '0';
                    a.pop();
                }
                else
                {
                    num = 1;
                }
                while (num--)
                {
                    for (j = 0; j<temp.size(); j++)
                    {
                        a.push(temp[j]);
                    }
                }
                temp.clear();
            }

        }
        while (!a.empty())
        {
            ans.insert(ans.begin(), a.top());
            a.pop();
        }
        cout << ans << endl;
    }



    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值