標籤:
#include<iostream> #include<string>#include<cstring>#include<cstdlib>#include<list>#include<map>using namespace std;class GLNode{ public: int tag; string node; class { public: GLNode *hp, *tp; } ptr;};typedef GLNode *GList;class MyGList{ public: static const int ERROR = -1; static const int OK = 1; static const int LIST = 2; static const int NODE = 3; list<string> sl;//廣義表的描述字串 map<string, string>mp; GList L = NULL; MyGList(list<string> sl){ this->sl = sl; initMap(); } void buildGList(){ string s = *sl.begin(); int pos = s.find_first_of("="); if(pos!=s.npos) createGList(L, s.substr(pos+1, s.length())); } void outGList(){ out(L); } private: void server(string &s, string &hs){ int k = 0;//記錄尚未匹配的左括弧的個數 int i = 0; for(i; i<s.length(); ++i) { if(s[i]==‘(‘) ++k; if(s[i]==‘)‘) --k; if(k==0 && s[i]==‘,‘) break; } if(i < s.length()){ hs = s.substr(0, i); s = s.substr(i+1, s.length()-(i+1)); } else { hs = s; s = ""; } } int initMap(){ for(list<string>::iterator i = sl.begin(); i!=sl.end(); ++i){ string s = *i, first, second; int pos = s.find_first_of("="); if(pos!=s.npos){ first = s.substr(0, pos); second = s.substr(pos+1, s.length()); } else { cout<<"廣義表的描述字串出錯!"<<endl; return ERROR; } mp.insert(make_pair(first, second)); } } void out(GList Lx){ if(!Lx) return; if(Lx->tag==NODE){ cout<<Lx->node<<endl; return; } for(GList p=Lx; p; p=p->ptr.tp) out(p->ptr.hp); } void createGList(GList &L, string s){ if(s=="()"){ //建立空表 L = NULL; } else { L = new GLNode;//因為類中有string變數,不能用malloc, 否者賦值無效 if(s.find(",")==s.npos && s.find("(")==s.npos && s.find(")")==s.npos){//原子結點 if(mp.find(s) == mp.end()){ L->tag = NODE; L->node = s; } else {//當s是只有一個大寫字母組成的時候,說明它是一個子表,繼續擴充 createGList(L, mp[s]);//這塊出了開始bug, 調了好長時間 } } else {//非原子結點 L->tag = LIST; GList p = L, q; s = s.substr(1, s.length()-2); do{ string hs; server(s, hs);//分離表頭 createGList(p->ptr.hp, hs); q = p; if(s!=""){//表尾不空 p = new GLNode; p->tag = LIST; q->ptr.tp = p; } }while(s!=""); q->ptr.tp = NULL; } } }};int main(){ freopen("in.txt", "r", stdin); list<string> sl; string s; while(cin>>s){ sl.push_back(s); } MyGList myGList(sl); myGList.buildGList(); myGList.outGList(); return 0;}
測試資料:
D=(A,B,C)
A=()
B=(e)
C=(a,(b,c,d))
資料結構複習之廣義表的建立和遍曆