广义表的创建及求其深度

xiaoxiao2021-02-28  23

#include<stdio.h> #include<stdlib.h> #include<string.h> typedef enum{ atom,list }ElemTag; struct node{ ElemTag  tag; union{ char s; struct node *head; }; struct node *tail; }; char a[100]; int len,time; int max=0; struct node* dfs(int step) { struct node*t; if(step>max) { max=step; } t=(struct node*)malloc(sizeof(struct node)); if(time==len-1) { return NULL; } if(a[time]=='(') //当遇到“(”时,便创建一个表头,然后去寻找它的头指针和尾指针指向的地方   { t->tag=list; time++; while(a[time]==',') { time++; } t->head=dfs(step+1); time++; while(a[time]==',') { time++; } if(a[time]==')')    //无论是表头还是原子,只要遇到“)”便指向NULL { t->tail=NULL; //time++; //while(a[time]==',') //{ // time++; //} return t; } if(a[time]>='a'&&a[time]<='z') { t->tail=dfs(step); //time++; //while(a[time]==',') //{ // time++;    // } return t; } if(a[time]=='(')   //如果表头的尾指针是"(",则他的尾指针指向的地方是表头 { t->tail=dfs(step); } } if(a[time]>='a'&&a[time]<='z') //这种情况他的尾指针指向的位置是一个原子 { t->tag=atom; time++;    while(a[time]==',')    {       time++;    }    t->tail=dfs(step);    return t; } if(a[time]==')') { return NULL; } } int main() { struct node *head1; gets(a); head1=(struct node*)malloc(sizeof(struct node)); len=strlen(a); head1->tag=list; //第一个位置肯定是表头,且该表头尾部肯定为空 time++; while(a[time]==',') { time++; }     head1->head=dfs(1);     head1->tail=NULL; printf("%d\n%d",max,max); return 0; }
转载请注明原文地址: https://www.6miu.com/read-2624694.html

最新回复(0)