1 回答

TA貢獻1883條經驗 獲得超3個贊
囧~~
#include <stdio.h>
#include <stdlib.h>
#define NULL 0
typedef enum{ATOM, LIST}ElemTag; /*ATOM==0:原子,LIST==1:子表*/
typedef struct GLNode
{
int tag; /*公共部分,區分原子和表結點*/
union /*原子結點和表結點的聯合部分*/
{
char atom; /*原子結點的值域*/
struct GLNode *sublist; /*表結點表頭指針*/
};
struct GLNode *next; /*下一個元素結點*/
}GList;
void CreateGList(GList **gl);
void PrintGList(GList *gl);
int GListDepth(GList *gl);
int main(void)
{
GList *gl;
printf("建立一個廣義表,以右括號結束\n");
CreateGList(&gl);
printf("輸出廣義表:");
PrintGList(gl);
printf("\n");
printf("廣義表的深度:");
printf("%d\n", GListDepth(gl->sublist));
return 0;
}
/*************************************************
函數名稱:CreateGList
函數功能:創建一個廣義表(遞歸構件子表)
輸入的時候是換一行輸入,最后要多輸右括號,是遞歸的原因
被本函數調用的函數清單:無
調用本函數的函數清單:無
輸入參數:gl,取用指針的指針的形式,可以對其直接修改
輸出參數:無
函數返回值:(void)
**************************************************/
void CreateGList(GList **gl)
{
char ch;
scanf("%c", &ch);
getchar(); /*吞食scanf留下的換行*/
if(ch == '#') /*如果輸入的是#表示為空*/
{
*gl = NULL;
}
else if(ch == '(') /*如果是左括號就遞歸構件子表*/
{
*gl = (GList *)malloc(sizeof(GList));
(*gl)->tag = LIST;
CreateGList(&((*gl)->sublist));
}
else /*就是只有原子的情況下*/
{
*gl = (GList *)malloc(sizeof(GList));
(*gl)->tag = ATOM;
(*gl)->atom = ch;
}
scanf("%c", &ch); /*此處輸入的必為逗號或者右括號*/
getchar();
if((*gl) == NULL)
{
;
}
else if(ch == ',') /*如果是逗號就遞歸構件下一個子表*/
{
CreateGList(&((*gl)->next));
}
else if(ch == ')') /*如果是右括號就結束*/
{
(*gl)->next = NULL;
}
}
/*************************************************
函數名稱:GListDepth
函數功能:求廣義表的深度(遞歸子表->到子表..(最長+1))
被本函數調用的函數清單:無
調用本函數的函數清單:無
輸入參數:gl
輸出參數:無
函數返回值:(void)
**************************************************/
int GListDepth(GList *gl)
{
int max, dep;
if(!gl)
return 1;
for(max = 0; gl; gl = gl->next)
{
if(gl->tag == LIST)
{
dep = GListDepth(gl->sublist); /*求以gl->sunlist的子表深度*/
if(dep > max)
{
max = dep;
}//if
}//if
}//for
return max + 1; /*各元素的深度的最大值加一*/
}
/*************************************************
函數名稱:PrintGList
函數功能:打印廣義表(遞歸打印子表)
被本函數調用的函數清單:無
調用本函數的函數清單:無
輸入參數:gl
輸出參數:無
函數返回值:(void)
**************************************************/
void PrintGList(GList *gl)
{
if(gl->tag == LIST)
{
printf("("); /*先輸出左括號*/
if(gl->sublist == NULL)
{
printf("#");
}
else
{
PrintGList(gl->sublist); /*遞歸打印子表*/
}
printf(")"); /*結束打印右括號*/
}
else
{
printf("%c", gl->atom);
}
if(gl->next != NULL) /*如果沒結束就繼續遞歸打印子表*/
{
printf(", ");
PrintGList(gl->next);
}
}
添加回答
舉報