下面是建立,插入,删除,显示动态链表的C程序,一般情况运行功能没问题,但当删除
"后插入的结点"时
程序的打印函数print却显示的数据总是比原先的少1
比如,数据是799,当要删除它时,程序的打印函数print却显示"798 deleted"(总是少1)
不知何故? 请高手看看,指点一下?
#include <stdio.h> #include <alloc.h> #define LEN sizeof(struct stu) struct stu { int num; char name[20]; int score; struct stu *next; }; int n; struct stu *new(void) { int flag=0; struct stu *head; struct stu *p1,*p2; n=0; head=NULL; p1=p2=NULL; printf("\ninput data:\n"); do { p1=(struct stu *)malloc(LEN); scanf("%d%s%d",&p1->num,p1->name,&p1->score); if(p1->num!=0) { n=n+1; if(n==1) head=p1; else p2->next=p1; p2=p1; } else flag=1; }while(flag!=1); p2->next=NULL; return(head); }
void print(struct stu *head) { struct stu *p; p=head; if(p==NULL) return; printf("\nthe records are:\n"); printf("%d %o\n",p,p); do { printf("%d %o %d %s %d %d %o\n",p,p,p->num,p->name,p->score,p->next,p->next); p=p->next; }while(p!=NULL); }
struct stu *del(struct stu *head,int num) { struct stu *p1,*p2; if(head==NULL) { printf("\nlist is NULL\n"); return(head); } p1=head; while(num!=p1->num&&p1->next!=NULL) { p2=p1; p1=p1->next; } if(num==p1->num) { if(p1==head) head=p1->next; else p2->next=p1->next; free(p1); printf("%d deleted\n",num); n=n-1; } else printf("%d not found!\n",num); return(head); }
struct stu *insert(struct stu *head,struct stu *s) { struct stu *p0,*p1,*p2; p1=head; p0=s; if(head==NULL) { head=p0; p0->next=NULL; } else { while((p0->num>p1->num)&&(p1->next!=NULL)) { p2=p1; p1=p1->next; } if(p0->num<=p1->num) { if(p1==head) { head=p0; p0->next=p1; } else { p2->next=p0; p0->next=p1; } } else { p1->next=p0; p0->next=NULL; } } n=n+1; return(head); }
main() { struct stu *p; struct stu a; int delnum; p=new(); print(p); printf("input the data to insert:\n"); scanf("%d%s%d",&a.num,a.name,&a.score); p=insert(p,&a); print(p); printf("input the number to delete:\n"); scanf("%d",&delnum); p=del(p,delnum); print(p); }