栈的模拟 Train Problem I

我这一周正式的开始了对数据结构和经典算法的学习,第一周内容就只有一点,栈的模拟

栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

https://vjudge.net/contest/276386#problem/B

题意:比较第二个数列是否能由第一个通过栈的操作得到;

代码如下:

#include <iostream>
#include <algorithm>
using namespace std;
const int N = 101;
int main()
{
    int n;
    char s1[N];
    char s2[N];
    char st[N];
    int value[N];
    while(cin >> n >> s1 >> s2)
    {
        int i = 0;
        int j = 0;
        int value_len = 0;
        int top = 0;
        while(s1[i] && s2[j])
        {
            st[top++] = s1[i];
            value[value_len++] = 0;
            i++;
            while(top > 0 && st[top - 1] == s2[j])
            {
                top--;
                value[value_len++] = 1;
                j++;
            }
        }
        if(!top)
        {
            cout << "Yes.\n";
            for(int i = 0; i < value_len; i++)
                if(value[i] == 0)
                    cout << "in\n";
                else
                    cout << "out\n";
        }
        else
            cout << "No.\n";
        cout << "FINISH\n";
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43993181/article/details/85269903