高手请帮我看看,我的链表到了 insert()和destroy()函数数据就不对,
程序代码:
/* Note:Your choice is C IDE */ #include "stdio.h" #include "stdlib.h" #include "conio.h" #include "alloc.h" #include "dos.h" #define NULL 0 #define LEN sizeof(struct student) struct student/* 定义结点结构类型 */ { int num; char name[9];/* 用于存放姓名 */ struct student *next;/* 用于指向下一个结点(后继结点) */ }; struct student *create() /*建立链表*/ { struct student *pHead=NULL; struct student *pEnd=pHead,*pS=NULL; int num; clrscr(); while (1) { printf("Please input student\'s number,0 return: "); scanf("%d",&num); if (num<1) { return(pHead);/*如果小余1返回*/ } pS=(struct student*)malloc(LEN); /*申请新结点空间*/ pS->num=num; printf("\nPlease input student\'s name: "); scanf("%s",pS->name); pS->next=NULL; if (pHead==NULL) /*如果链表为空,新结点为表头*/ { pHead=pS; } else { pEnd->next=pS; } pEnd=pS; } } void showlist(struct student *pHead) /*输出链表所有数据*/ { clrscr(); while (1) { if(pHead==NULL) /*为空输出:The end*/ { printf("The end"); getch(); break; } printf("Student\'s number is: %d student\'s name is: %s\n",pHead->num,pHead->name); pHead=pHead->next; } } struct student *search(struct student *pHead,int num) { struct student *pS=pHead; while (1) { if(pS->num==num||pS==NULL) { return(pS); } pS=pS->next; } } int insert(struct student *pHead) { struct student *pS=NULL,*pSN=NULL; int num; char name[9]; showlist(pHead); printf("\n请输入要在其后插入的学号。"); scanf("%d",&num); pS=search(pHead,num); if(pS==NULL) { printf("\nCoundn't search this student."); getchar(); } else { pSN=(struct student*)malloc(LEN); /*申请新结点空间*/ printf("Please input student\'s number: "); scanf("%d",pSN->num); printf("\nPlease input student\'s name: "); scanf("%s",pSN->name); pSN->next=pS->next; pS->next=pSN; return(1); } return(0); } void destroy(struct student *pHead) { struct student * pS=pHead; while (pHead!=NULL) { pS=pHead; pHead=pHead->next; free(pS); } } int main() { char chl;/* 存放选项*/ char blank[]=" ";/*用来格式控制*/ struct student *pHead,*pS; int num; while (1) { clrscr(); printf("\n\n\n\n\n\n");/*用天格式控制*/ printf("%s 1 Create new list.\n",blank); printf("%s 2 Show list.\n",blank); printf("%s 3 search record.\n",blank); printf("%s 4 Insert record.\n",blank); printf("%s 5 Delete record.\n",blank); printf("%s 6 Destroy list.\n",blank); printf("%s 0 Exit.\n\n",blank); printf("%s Please enter 0-6: ",blank); chl=getch(); switch (chl) { case '1':pHead=create(); chl='q';break;/* 以head 为表头创建一个链表 */ case '2':showlist(pHead);/* 遍历以 head 为表头的链表 */ break; case '3':clrscr(); printf("Please input the student\'s number: ");/*查找指定学号的记录*/ scanf("%d",&num); pS=search(pHead,num); if(pS==NULL) { printf("\nCoundn't search this student."); } else { printf("\nStudent\'s number is: %d student\'s name is: %s\n",pS->num,pS->name); } getch(); break; case '4':insert(pHead); break; case '5':printf("You input 5!\n");getch(); break; case '6':destroy(pHead); break; case '0':destroy(pHead); exit(1); default :printf("Please input 0-5!\n");getch(); } } }选择4 插入数据不对,删除链表也有错,高手帮我看看。