3-29堆栈的应用

 

#include<iostream>
#include<stdio.h>
#include<stack>
#include<string>
using namespace std;
struct str{
    char x;
    int loc;
};
stack<str> s;
int main()
{
    string z;
    while(cin >> z)
    {
        str tmp;
        for(size_t ix = 0; ix != z.size(); ix ++)
        {
            if(z[ix] == ')')
            {
                tmp.x = z[ix];
                tmp.loc = ix;
                if(s.empty())
                    s.push(tmp);    
                else if(s.top().x == '(')
                    s.pop();
                else
                {
                    s.push(tmp);
                }
            }
            else if(z[ix] == '(')
            {
                tmp.x = z[ix];
                tmp.loc = ix;
                s.push(tmp);
            }
        }
        cout << z << endl;
        char *p = new char [z.size()]();
        while(!s.empty())
        {
            p[s.top().loc] = s.top().x;
            s.pop();
        }
        for(int i = 0; i != z.size(); i++)
        {
            if(*(p + i) != '(' && *(p + i) != ')')
                printf(" ");
            else if(*(p + i) == '(')
                printf("$");
            else
                printf("?");
        }
        printf("\n");
    }
    return 0;
}

 

posted on 2013-03-31 18:32  lgy111  阅读(168)  评论(0)    收藏  举报

导航