礼盒问题

#include 
#include 
#include 
#include 
#include 

using namespace std;

struct Node
{
    int is_box;
    string item;
    vector childs;
};

void splie_contents(string str, vector & contents)
{
    int pos = 0;
    int start;
    int end;
    stack  st;

    while(pos < str.size()) {
        pos = str.find(',');
        if(pos == string::npos) {
            contents.push_back(str);
            break;
        } else {
            contents.push_back(str.substr(0, pos));
        }

        pos++;
        if(str[pos] == '[') {
            start = pos;
            end = start+1;
            st.push(start);

            while(!st.empty() && end < str.size()) {
                if(str[end] == '[') {
                    st.push(end);
                } else if(str[end] == ']') {
                    st.pop();
                }

                end++;
            }

            contents.push_back(str.substr(start, end-start));
            pos = end+1;
        }

        if(pos < str.size()) {
            str = str.substr(pos);
        }
    }
}

struct Node *build_tree(string str)
{
    struct Node *root;
    struct Node *child;
    vector  contents;
    int pos = 0;

    cout << "build_tree: " << str << endl;

    root = new struct Node;

    /*items*/
    if(str[0] != '[') {
        root->is_box = 0;
        root->item = str;
        return root;
    }

    /*empty box*/
    if(str[0] == '[' && str[1] == ']') {
        root->is_box = 1;
        return root;
    }

    root->is_box = 1;

    /*split all items*/
    splie_contents(str.substr(1, str.size() - 2), contents);
    for(int i=0; i::iterator it = contents.begin(); it < contents.end(); it++) {
        cout << *it << " ";
        child = build_tree(*it);
        root->childs.push_back(child);
    }

    cout << endl;

    return root;
}

void print_tree(struct Node *root)
{
    queue  que;
    struct Node *node;
    struct Node *flag;

    que.push(root);
    flag = root;

    while(!que.empty()) {
        node = que.front();

        if(!node->is_box) {
            cout << node->item << " ";
        } else {
            cout << "[] ";
        }

        if(node == flag) {
            if(!node->childs.empty()) {
                flag = node->childs[node->childs.size()-1];
            }

            cout << endl;
        }

        for(vector ::iterator it = node->childs.begin(); itchilds.end(); it++) {
            que.push(*it);
        }

        que.pop();
    }
}

int main(int argc, char **argv)
{
    //string str("[T-shirt,[doll,[dog,cat],[]]]");
    string str("[doll,[dog,cat],[]]");
    struct Node *root;

    root = build_tree(str);
    print_tree(root);

    return 0;
}

你可能感兴趣的:(礼盒问题)