文档详情

程序设计9结构体和联合体0.ppt

发布:2018-06-25约2.06万字共45页下载文档
文本预览下载声明
#includestdio.h #includemalloc.h main() { int *p,i; p=calloc(10,sizeof(int)); for(i=0;i10;i++,p++) *p=2*i; p=p-10; clrscr(); for(i=0;i10;i++,p++) printf(%d,,*p); } 动态链表的建立和遍历示例 (后进先出的数据结构,即所谓“栈”) #define NULL 0 struct info { int data; struct info *next; }; main() { struct info *base,*p; int n; base=NULL; for(n=0;n10;n++) { p=(struct info *)malloc(sizeof(struct info)); p-data=n+1; p-next=base; base=p; } while (p!=NULL) { printf(%4d,p-data); p=p-next; } } 结果:10 9 8 7 6 5 4 3 2 1 动态链表的建立和遍历示例 #define NULL 0 struct info { long num; int score; struct info *next; }; main() { struct info *head,*p1,*p2; int n=1; clrscr(); head=p1=p2=(struct info *)malloc(sizeof(struct info)); printf(请输入第%d个同学的学号和成绩:,n++); scanf(%ld,%d,p1-num,p1-score); while(p1-num!=0) { p1=(struct info *)malloc(sizeof(struct info)); if(!p1){ printf(内存分配出错! ); exit(); } printf(请输入第%d个同学的学号和成绩:,n++); scanf(%ld,%d,p1-num,p1-score); p2-next=p1; p2=p1; } p2-next=NULL; p1=head; while(p1-next!=NULL) { printf(%ld,%d\n,p1-num,p1-score); p1=p1-next; } } 对链表的删除操作 struct student *del(struct student *head,long num) { struct student *p1,*p2; if (head==NULL) {printf(\n空链表!\n); goto end;} p1=head; while (num!=p1-nump1-next!=NULL) { p2=p1;p1=p1-next;} /*非所找结点且非未结点后移*/ if(num==p1-num) /*找到了*/ { if (p1==head) head=p1-next; /*为首结点*/ else p2-next=p1-next; /*非首结点*/ printf(delete:%ld\n,num); n=n-1; } else printf(“%ld not been found!\n”,num); /*未找到*/ end: return(head); } 对链表的插入操作 struct student *insert(struct student *head,struct student *stud) { struct student *p0,*p1,*p2; p1=head; /*p1指向第一个结点*/ p0=stud; /*p0指向要插入的结点*/ if(head==NULL) /*如为空链表*/ {head=p0;p0-next=NULL;} else {whi
显示全部
相似文档