May 27

根据给出的括号表达式字符串建立二叉树 不指定

felix021 @ 2009-5-27 02:17 [IT » 程序设计] 评论(1) , 引用(0) , 阅读(7222) | Via 本站原创 | |
突然想写了,就写了一个。
因为调试需要,自己写了一个stack,继承vector实现(如果是继承自通用stack类的话那就是个类适配器了哦^_^)

代码如下:
#include<iostream>
#include<vector>
using namespace std;

struct node_t{
    char data;
    node_t *left, *right;
    node_t(){
        data = '\0';
        left = NULL;
        right = NULL;
    }
    ~node_t() {
        delete left;
        delete right;
    }
    friend inline ostream & operator << (ostream &os, const node_t &t){
        os << t.data << "(" << t.left << "," << t.right << ")";
        return os;
    }
}*root;
void print(node_t **t){
    if(*t == NULL){
        cout << 0;
    } else {
        cout << *t << "|" << (**t);
    }
}

void dump(node_t *t = root, int dep = 0){
    if(t != NULL){
        for(int i = 0; i < dep; ++i) printf("  ");
        print(&t);
        printf("\n");
        dump(t->left, dep+1);
        dump(t->right, dep+1);
    }
}

template<typename T>
class mystack: private vector<T>{ //很少使用private继承哦,嘿嘿。
public:
    void push(const T &a){
        this->push_back(a);
    }
    void pop(){
        this->pop_back();
    }
    T & top(){
        return *(this->rbegin());
    }
    void dump(void (*print)(T)){
        for(unsigned int j = 0; j < this->size(); ++j){
            print(this->operator[](j));
            cout << ',' ;
        }
        cout << endl;
    }
};

node_t* build(char *s){
    mystack<node_t**>ooxx;
    node_t *root = new node_t, **t;
    ooxx.push(&root);
    for(int i = 0; s[i] != '\0'; ++i){
        printf("procesing %c\n", s[i]);
        switch(s[i]){
            case ' ':
                break;
            case '(':
                t = ooxx.top();
                ooxx.push(&((*t)->left));
                break;
            case ',':
                ooxx.pop();
                t = ooxx.top();
                ooxx.push(&((*t)->right));
                break;
            case ')':
                ooxx.pop();
                break;
            default:
                t = ooxx.top();
                if(*t == NULL) *t = new node_t;
                (*t)->data = s[i];
                break;
        }
        ooxx.dump(print);
    }
    return root;
}

int main(){
    root = build("a(b(,e(f,g(h(j,),i(k,)))),c(d,))");
    dump(root);
    return 0;
}




欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
luoxi0209
2009-5-27 11:24
膜拜ooxx
felix021 回复于 2009-5-27 12:38
......
分页: 1/1 第一页 1 最后页
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]