最近遇到一个了问题,就是要从普通文本文件中读取数据,这些数据是自定义的格式的层次结构,要把这些数据转化成嵌套的链表存储起来。
数据格式如下:
begin
111
begin
222
begin
333
end
444
begin
555
end
666
end
777
begin
888
end
999
begin
000
end
aaa
end
如果用缩进表示就是下面的样子了:
begin
111
begin
222
begin
333
end
444
begin
555
end
666
end
777
begin
888
end
999
begin
000
end
aaa
end
我的解析程序如下:
- #include <string>
- #include <iostream>
- #include <fstream>
- #include <stack>
- #include <list>
- using namespace std;
- typedef struct tagNode Node;
- typedef struct tagNode
- {
- string str;
- list<Node*>* pSubList;
- } Node;
- void PrintList(list<Node*>* pList, int* piCnt)
- {
- ++*piCnt;
- for (list<Node*>::iterator it = pList->begin(); it != pList->end(); ++it)
- {
- for (int i = 0; i < *piCnt; ++i)
- cout << "/t";
- cout << (*it)->str << endl;
- if ((*it)->pSubList != NULL)
- {
- PrintList((*it)->pSubList, piCnt);
- --*piCnt;
- }
- }
- }
- int main()
- {
- ifstream cin("data");
- stack<Node*> stk;
- list<Node*>* pList = NULL;
- string str;
- Node* pParent = NULL;
- Node* pNew = NULL;
- cin >> str;
- if (str == "begin")
- {
- cin >> str;
- pNew = new Node;
- pNew->str = str;
- pNew->pSubList = NULL;
- pList = new list<Node*>;
- pList->insert(pList->begin(), pNew);
- stk.push(pNew);
- }
- while (!stk.empty())
- {
- cin >> str;
- if (str == "begin")
- {
- cin >> str;
- pNew = new Node;
- pNew->str = str;
- pNew->pSubList = NULL;
- pParent = stk.top();
- pParent->pSubList = new list<Node*>;
- pParent->pSubList->insert(pParent->pSubList->begin(), pNew);
- stk.push(pNew);
- }
- else if (str == "end")
- {
- stk.pop();
- }
- else
- {
- stk.pop();
- pNew = new Node;
- pNew->str = str;
- pNew->pSubList = NULL;
- if (stk.size() > 0)
- {
- pParent = stk.top();
- pParent->pSubList->insert(pParent->pSubList->end(), pNew);
- }
- else
- {
- pList->insert(pList->end(), pNew);
- }
- stk.push(pNew);
- }
- }
- int iCnt = -1;
- PrintList(pList, &iCnt);
- return 0;
- }
运行结果如下: