第十二章——动态数据结构——课后作业及参考答案 第 1 页 共 9 页 第十二章_动态数据结构 12.1 设有变量说明 int *p1,*p2,*p3 , 指出下列程序段的执行结果。 1) p1=(int*)malloc(sizeof(int)); p2=(int*)malloc(sizeof(int)); *p1=9; *p2=5*(*p1 % 5); p3=p1; p1=p2; p2=p3; printf(“%5d%5d%5d\n”,*p1,*p2,*p3); 2) p1=(int*)malloc(sizeof(int)); *p1=25; p3=(int*)malloc(sizeof(int)); *p3 = *p1; p2=(int*)malloc(sizeof(int)); *p2=3; *p3 = *p3 / *p2; *p2 = *p1 / *p3; printf(“%5d%5d%5d\n”,*p1,*p2,*p3); 3) p1=(int*)malloc(sizeof(int)); *p1=5; p2=(int*)malloc(sizeof(int)); *p2=8; *p1 = *p1 + *p2; printf(“d%5d%5d\n”,*p1,*p2); 4) p1=(int*)malloc(sizeof(int)); *p1=12; p2=p1; p1=(int*)malloc(sizeof(int)); *p1 = *p2+7; printf(“d%5d%5d\n”,*p1,*p2); 参考答案: 2 0 9 9 2 5 3 8 d 1 3 8 d 1 9 1 2 12.2 设有数据类型如下: struct tr { int d ; struct tr *n ; } 分别用循环和递归方法编函数,求结点类型为 tr 的链表长度。 参考答案: 第十二章——动态数据结构——课后作业及参考答案 第 2 页 共 9 页 循环方法: #include "stdlib.h" #include"malloc.h" struct tr{ int d; struct tr *n; }; int len(struct tr *x){ int l=0; struct tr *tp=x; while(tp!=NULL){ l++; tp=tp->n; } return l; } void main(){ struct tr *tr1=(struct tr*)malloc(sizeof(struct tr)); struct tr *tr2=(struct tr*)malloc(sizeof(struct tr)); struct tr *tr3=(struct tr*)malloc(sizeof(struct tr)); tr1->d=1; tr2->d=2; tr3->d=3; tr1->n=tr2; tr2->n=tr3; tr3->n=NULL; printf("%d\n",len(tr1)); } 递归方法: #include "stdlib.h" #include "stdio.h" struct tr{ int d; struct tr *n; }; int len(struct tr *x){ if(x==NULL) return 0; else return len(x->n)+1; } void main(){ struct tr *tr1=(struct tr*)malloc(sizeof(struct tr)); struct tr *tr2=(struct tr*)malloc(sizeof(struct tr)); struct tr *tr3=(struct tr*)malloc(sizeof(struct tr)); struct tr *tr4=NULL; tr1->d=1; tr2->d=2; tr...