广义表的简单运用实例(导师制)--广义表的建立和输出

来源:互联网 发布:延迟选择实验 知乎 编辑:程序博客网 时间:2024/06/05 09:27
//head.htypedef struct GLNode{char name[100];char prof[100];int type;struct {/*理解:hp是同级关系,tp是上下级关系*/struct GLNode* hp, *tp;}ptr;}GList;


//test.cpp#include"head.h"#include<iostream>#include<cstdio>#include<cstdlib>using namespace std;GList* creatList(char * str){/*p为导师,q为研究生,a为本科生,m为新开辟节点*/GLNode *head, *p, *q, *a, *m;int i = 0, j = 0, flag = 0, flag1 = 0, flag2 = 0, len = strlen(str);head = p = q = m = a = NULL;while (i<len){if (str[i] == '(' || str[i] == ')'|| str[i] == ','){i++;continue;}else{if (!(m = (GList*)malloc(sizeof(GList))))exit(1);for (j = 0; str[i] != '-';){m->name[j++] = str[i++];}m->name[j] = '\0';//cout << "当前建立节点的姓名为:" << m->name << endl;/*注意要++i,省略掉掉-*/for (j = 0, ++i; str[i] != '-';){m->prof[j++] = str[i++];}m->prof[j] = '\0';//cout << "当前建立节点的属性为:" << m->prof << endl;/*注意要++i,省略掉掉-*/m->type = str[++i] - 48;//cout << "当前建立节点的编号为:" << m->type << endl;m->ptr.hp = m->ptr.tp = NULL;/*注意要++i,省略掉掉),才能使下一次开始时i的位置正确*/i++;/*导师*/if (m->type == 0){if (flag)    /*非首节点*/{p->ptr.hp = m;p = m;}else         /*首节点*/{head = p = m;flag = 1;}flag1 = 0;a = q = m;}/*研究生*/else if (m->type == 1){if (flag1)   /*非首节点*/{q->ptr.hp = m;q = m;}else       /*首节点*/{q->ptr.tp = m;q = m;flag1 = 1;}flag2 = 0;a = m;}/*本科生*/else{                                             if (flag2)    /*非首节点*/{a->ptr.hp = m;a = m;}else         /*首节点*/{a->ptr.tp = m;a = m;flag2 = 1;}}}}return head;}/*按照深度优先输出*/void GListPrint(GList *head){GList *p, *q, *a;int flag = 0, flag1 = 0, flag2 = 0;p = head;printf("(");while (true){                  /*导师范围*/if (p == NULL)break;if (flag)printf(",(%s-%s-%d", p->name, p->prof, p->type);else{printf("(%s-%s-%d", p->name, p->prof, p->type);flag = 1;}q = p->ptr.tp;flag1 = flag2 = 0;while (true){               /*研究生或本科生范围*/if (q == NULL)break;if (flag1){if (q->type == 1)printf(",(%s-%s-%d", q->name, q->prof, q->type);elseprintf(",%s-%s-%d", q->name, q->prof, q->type);}else{printf(",(%s-%s-%d", q->name, q->prof, q->type);flag1 = 1;}a = q->ptr.tp;flag2 = 0;while (true){/*本科生范围*/if (a == NULL)break;if (flag2)printf(",%s-%s-%d", a->name, a->prof, a->type);else{printf(",(%s-%s-%d", a->name, a->prof, a->type);flag2 = 1;}a = a->ptr.hp;}if (flag2) printf(")");if (q->type == 1 || q->ptr.hp == NULL)printf(")");q = q->ptr.hp;}printf(")");p = p->ptr.hp;}printf(")");}int main(){GList* head;char * data = "((高老师-教授-0,(李明-一班-1,王平-二班-2)),(李老师-副教授-0,(白梅-二班-1,(李刚-一班-2))))";head=creatList(data);GListPrint(head);}


0 0
原创粉丝点击