试按表头、表尾的分析方法编写求广义表的深度的递归程序。 |
输入一串以‘(’开始,以‘(’结束的字符串,并且输入的左右括号必须匹配,如:(),(())…… |
分别输出按表头、表尾分析方法求广义表深度的结果,每个结果占一行。 |
((a,b,(c,(d,e),f)),g) |
4 4 |
- #include <stdio.h>
- #include <stdlib.h>
- struct Node
- {
- int judge;
- struct Node *before;
- struct Node *next;
- union
- {
- struct Node *down;
- char data;
- };
- };
- void createGeneralNode (struct Node *pre);
- void createGeneralList (struct Node *head);
- void run ();
- int getDepth (struct Node *node);
- int main()
- {
- run ();
- return 0;
- }
- void createGeneralNode (struct Node *pre)
- {
- char s,ss=0;
- struct Node *cur;
- if ((s=getchar())==',')
- {
- ss=s;
- s=getchar();
- }
- if (s>='a'&&s<='z')
- {
- cur =(struct Node *)malloc (sizeof(struct Node));
- if (ss==',')
- {
- pre->next=cur;
- }
- else
- {
- pre->down=cur;
- }
- cur->before=pre;
- cur->data=s;
- cur->next=NULL;
- cur->judge=1;
- createGeneralNode (cur);
- }
- else
- {
- if (s=='(')
- {
- cur =(struct Node *)malloc (sizeof(struct Node));
- if (ss==',')
- {
- pre->next=cur;
- }
- else
- {
- pre->down=cur;
- }
- cur->before=pre;
- cur->down=NULL;
- cur->next=NULL;
- cur->judge=0;
- createGeneralNode (cur);
- }
- else
- {
- if (s==')')
- {
- while (pre->judge||pre->next)
- {
- pre=pre->before;
- }
- createGeneralNode (pre);
- }
- }
- }
- }
- void createGeneralList (struct Node *head)
- {
- head->judge=0;
- head->down=NULL;
- head->next=NULL;
- head->before=NULL;
- createGeneralNode(head);
- }
- void run ()
- {
- struct Node head;
- int depth;
- createGeneralList(&head);
- depth=getDepth(head.down);
- printf ("%d\n%d",depth,depth);
- }
- int getDepth (struct Node *node)
- {
- int max=0,depth;
- struct Node *p;
- for (p=node->next;p;p=p->next)
- {
- if (p->judge)
- {
- depth=0;
- }
- else
- {
- if (p->down)
- {
- depth=getDepth(p->down)+1;
- }
- else
- {
- depth=1;
- }
- }
- max=depth>max?depth:max;
- }
- if (node->judge)
- {
- depth=0;
- }
- else
- {
- if (node->down)
- {
- depth=getDepth(node->down)+1;
- }
- else
- {
- depth=1;
- }
- }
- return max=depth>max?depth:max;
- }