创建广义表

来源:互联网 发布:买房最好的软件 编辑:程序博客网 时间:2024/04/29 17:20

#include<stdio.h>
#include <stdlib.h>
#include<string.h>

#define OK 1
#define ERROR 0

typedef enum {ATOM,LIST} ElemTag;
typedef struct GLNode
{
    ElemTag tag;
    union
    {
        char atom;
        struct
        {
            struct GLNode *hp,*tp;
        } ptr;
    };
}*GList;

struct GLNode L;

typedef int Status;

Status CreateGList(GList L,char S[])
{
    int i,j;
    char emp[3]="()";
    char hsub[100];
    GList p,q;
    if (strcmp(S,emp)==0) L = NULL;  // 创建空表
    else
    {
        if (!( L= (GList) malloc (sizeof(struct GLNode)))) return ERROR;  // 建表结点
        if (strlen(S)==1)    // 创建单原子广义表
        {
            L->tag = ATOM;
            L->atom =S[0];
            printf("%c ",L->atom);

        }
        else
        {
            L->tag = LIST;
            p = L;
            for(i=0; i<strlen(S)-2; i++)  // 脱外层括号
                S[i]=S[i+1];
            S[i]='\0';

            do     // 重复建n个子表
            {
                // 从s中分离出表头串 hsub
                if(S[0]!='(')
                {
                    hsub[0]=S[0];
                    hsub[1]='\0';
                    for(j=0,i=2; i<=strlen(S); i++)
                        S[j++]=S[i];
                    S[j]='\0';
                }

                else
                {

                    for(j=0,i=0; i<strlen(S); i++)
                    {
                        if(S[i]=='(')
                            j++;
                        if(S[i]==')')
                            j--;
                        if(j==0)
                            break;
                    }
                    for(j=0; j<=i; j++)
                    {
                        hsub[j]=S[j];
                    }
                    hsub[j]='\0';

                    for(i=0; j<strlen(S); )
                    {
                        S[i++]=S[++j];
                    }
                    S[i]='\0';
                }
                CreateGList(p->ptr.hp, hsub);
                q = p;
                if (S[0]!='\0')     // 表尾不空
                {
                    if (!(p = (GList) malloc (sizeof(struct GLNode)))) return ERROR;
                    p->tag = LIST;
                    q->ptr.tp = p;
                }

            }
            while (S[0]!='\0');
            q->ptr.tp = NULL;
        }
    }
    return OK;
}
void main()
{
    int i;
    char S[100];
    printf("输入广义表:");
    gets(S);
    CreateGList(&L,S);
}

 
运行结果:
 
 
原创粉丝点击