标签:blog http ar io sp on 文件 数据 2014
文件glist.h头文件如下
#ifndef _GLIST_H_
#define _GLIST_H_
typedef enum {ATOM,LIST}ElemTag;
typedef struct _GList
{
ElemTag tag;
union
{
char data;
struct _GList *sublist;
}val;
struct _GList *next;
}GList,*pGList;
int glist_length(pGList pgl);
int glist_depth(pGList pgl);
pGList creat_glist(char **ch);
void printf_glist(pGList pgl);
#endif
数据结构实现glist.c如下
/************************
时间:2014.12.15
作者:XIAO_PING_PING
编译环境:DEV-C++ 4.9.9.2
内容:广义表的递归表示与实现
功能:学习写数据结构
*************************/
#include <string.h>
#include <stdlib.h>
#include "glist.h"
/*广义表的长度*/
int glist_length(pGList pgl)
{
int length = 0;
pgl = pgl->val.sublist;
while(pgl)
{
length++;
pgl = pgl->next;
}
return length;
}
/*广义表的深度*/
int glist_depth(pGList pgl)
{
int max = 0,depth;
if(0 == pgl->tag)
{
return 0;
}
pgl = pgl->val.sublist;
if(!pgl)
{
return 1;
}
while(pgl)
{
if(pgl->tag)
{
depth = glist_depth(pgl);
if(depth > max)
{
max = depth;
}
}
pgl = pgl->next;
}
return max+1;
}
/*创建广义表*/
pGList creat_glist(char **ch)
{
pGList pgl;
if(NULL == ch)
{
return ;
}
char tch = *(*ch);
*ch = *ch + 1;
if('\0' != tch)
{
pgl = (GList *)malloc(sizeof(GList));
if('(' == tch)
{
pgl->tag = LIST;
pgl->val.sublist = creat_glist(ch);
}
else if(')' == tch)
{
pgl = NULL;
}
else
{
pgl->tag = ATOM;
pgl->val.data = tch;
}
}
else
{
pgl = NULL;
}
tch = *(*ch);
*ch = *ch + 1;
if(pgl)
{
if(',' == tch)
{
pgl->next = creat_glist(ch);
}
else
{
pgl->next = NULL;
}
}
return pgl;
}
/*遍历打印广义表*/
void printf_glist(pGList pgl)
{
if(pgl)
{
if(1 == pgl->tag)
{
printf("(");
if(pgl->val.sublist)
{
printf_glist(pgl->val.sublist);
}
else
{
printf(" ");
}
}
else
{
printf("%c",pgl->val.data);
}
if(1 == pgl->tag)
{
printf(")");
}
if(pgl->next)
{
printf(",");
printf_glist(pgl->next);
}
}
}
测试文件test.c如下:
/***************************************
时间:2014.12.15
作者:XIAO_PING_PING
****************************************/
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include "glist.h"
int main()
{
int length,depth;
char *s="(a,(b,c,d),(d,l),d,p))";
pGList gl;
gl = creat_glist(&s);
length = glist_length(gl);
depth = glist_depth(gl);
printf("length = %d,depth = %d\n",length,depth);
printf_glist(gl);
getch();
return 0;
}
运行结果如下:
标签:blog http ar io sp on 文件 数据 2014
原文地址:http://blog.csdn.net/xiao_ping_ping/article/details/41951339