这个广义表构造以及求深度运行后结果不对,有什么问题
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef enum{
ATOM, LIST
} TagType;
typedef char AtomType;
typedef union {
struct GLNode *hp, *tp;
AtomType atom;
} PTR;
typedef struct GLNode {
TagType tag;
PTR ptr;
} GLNode, *GList;
// 相应的字符串算法
int StringLength(char* str) {
int i = 0;
while (str[i] != '\0') {
++i;
}
return i;
}
void SubString(char* str, char* sub, int begin, int end) {
if (begin < 0 || end >= StringLength(str)) {
exit(0);
}
for (int i = begin; i <= end; i++) {
sub[i - begin] = str[i];
}
//sub[end - begin + 1] = '\0'; // 添加结束符
}
int StringEmpty(char* str) {
if (str == NULL || *str == '\0') {
return 1;
}
return 0;
}
void sever(char* sub, char* hsub) {
int n = StringLength(sub);
int i = 0;
int k = 0;
do {
++i;
if (sub[i] == '(') {
k++;
}
else if (sub[i] == ')') {
k--;
}
} while (i < n && (sub[i] != ',' || k != 0));
if (i < n) {
SubString(sub, hsub, 1, i - 1);
SubString(sub, sub, i + 1, n - 1);
}
else {
for (int i = 0; i < n; i++) {
hsub[i] = sub[i];
sub[i] = '\0';
}
}
}
// 相应的字符串算法
void CreateGList(GList *L, char* str) {
if (strcmp(str,"()") || StringEmpty(str)) {
*L = NULL;
}
else {
if (!(*L = (GList)malloc(sizeof(GLNode)))) {
exit(0);
}
int len = StringLength(str);
if (len == 1) { // 严女士提供的算法原子仅单字符
(*L)->tag = ATOM;
(*L)->ptr.atom = *str;
}
else {
(*L)->tag = LIST;
char* sub = (char*)malloc(len * sizeof(char));
char* hsub = (char*)malloc(len * sizeof(char));
SubString(sub, str, 1, len - 2);
GList p = *L;
GList q;
do {
sever(sub, hsub);
q = p;
CreateGList(&(p->ptr.hp), hsub);
if (!(p = (GList)malloc(sizeof(GLNode)))) {
exit(0);
}
p->tag = LIST;
q->ptr.tp = p;
} while (!StringEmpty(sub)); // 很好的迭代思想
q->ptr.tp = NULL;
free(sub); // 释放动态内存
free(hsub);
}
}
}
// 时间复杂度: O(广义表长度)
int GListDepth(GList L) {
if (!L) {
return 1;
}
if (L->tag == ATOM) {
return 0;
}
int max = 0;
int dep = 0;
for (GList p = L; p; p = p->ptr.tp) {
dep = GListDepth(p->ptr.hp);
if (dep > max) max = dep;
}
return max + 1;
}
// 时间复杂度: O(节点数)
int main() {
char* str = "((),(e),(a,(b,(f,(w,n),q),c,d)))";
GList L;
CreateGList(&L, str);
printf("success\n");
printf("%d\n", GListDepth(L));
return 0;
}