#include<iostream>
using namespace std;
enum NodeType
{
HEAD_TYPE,
SUB_TYPE,
VALUE_TYPE,
};
struct GeneralListNode
{
GeneralListNode* _next;
NodeType _type;
union
{
char _value;
GeneralListNode* _sub;
};
GeneralListNode(NodeType type = HEAD_TYPE,char value = '\0')
:_next(NULL)
,_type(type)
{
if(type == VALUE_TYPE)
_value = value;
if(type == SUB_TYPE)
_sub = NULL;
}
};
class GeneralList
{
public:
GeneralList(const char* str)
:_link(NULL)
{
_CreateGeneralList(_link,str);
}
GeneralList(GeneralList& g)
{}
GeneralList& operator=(GeneralList& g)
{}
~GeneralList()
{
_Destory(_link);
}
void Print()
{
_Print(_link);
cout << endl;
}
int Size()
{
return _Size(_link);
}
int Depth()
{
return _Depth(_link);
}
protected:
void _Destory(GeneralListNode* head)
{
while(head)
{
if(head->_type == SUB_TYPE)
{
_Destory(head->_sub);
}
GeneralListNode* temp = head;
head = head->_next;
delete temp;
}
}
int _Depth(GeneralListNode* head)
{
GeneralListNode* cur = head;
int depth = 1;
while(cur)
{
if (cur->_type == SUB_TYPE)
{
int subDepth = _Depth(cur->_sub);
if (subDepth + 1 > depth)
{
depth = subDepth + 1;
}
}
cur = cur->_next;
}
return depth;
}
int _Size(GeneralListNode* head)
{
int size = 0;
GeneralListNode* cur = head;
while(cur != NULL)
{
if(cur->_type == VALUE_TYPE)
{
size++;
}
if(cur->_type == SUB_TYPE)
{
size += _Size(cur->_sub);
}
cur = cur->_next;
}
return size;
}
void _Print(GeneralListNode* link)
{
GeneralListNode* begin = link;
while(begin)
{
if(begin->_type == HEAD_TYPE)
{
cout<<"(";
}
else if(begin->_type == VALUE_TYPE)
{
cout << begin->_value;
if (begin->_next)
{
cout<<",";
}
}
else if(begin->_type == SUB_TYPE)
{
_Print(begin->_sub);
if (begin->_next)
{
cout<<",";
}
}
begin = begin->_next;
}
cout<<")";
}
bool _IsValueChar(char ch)
{
if(ch >= 'a' && ch <= 'z'
|| ch >= '0'&& ch <= '9'
|| ch >='A'&& ch <= 'Z')
return true;
else
return false;
}
void _CreateGeneralList(GeneralListNode*& link,const char*& str)
{
if(*str++ != '(')// 使str往后面走了一步
exit(-1);
GeneralListNode* head = new GeneralListNode(HEAD_TYPE);
link = head;
GeneralListNode* begin = head;
while(*str != '\0')
{
if(_IsValueChar(*str)) // 如果就是值结点的话那么创建值结点
{
GeneralListNode* temp = new GeneralListNode(VALUE_TYPE,*str);
str++; // 这里的加加是跳过逗号和右括号
begin->_next = temp;
begin = begin->_next;
}
else if(*str == '(')
{
//创建子表
GeneralListNode* temp = new GeneralListNode(SUB_TYPE);
begin->_next = temp;
begin = begin->_next;
_CreateGeneralList(temp->_sub,str);
}
else if(*str == ')')
{
++str;
return;
}
else
{
++str;
}
}
}
private:
GeneralListNode* _link;
};
void Test()
{
const char* str1 = "()";
GeneralList gl1(str1);
gl1.Print();
const char* str2 = "(a,b)";
GeneralList gl2(str2);
gl2.Print();
const char* str3 = "(a,b,(c,d))";
GeneralList gl3(str3);
gl3.Print();
cout<<gl3.Size()<<endl;;
cout<<gl3.Depth();
cout<<endl;
const char* str4 = "(a,b,(c,d),(e,(f),h))";
GeneralList gl4(str4);
gl4.Print();
cout<<gl4.Size()<<endl;
cout<<gl4.Depth();
cout<<endl;
}
int main()
{
Test();
return 0;
}