| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 688 人关注过本帖
标题:出现一个奇怪的C问题: 高手看看,指点一下?
取消只看楼主 加入收藏
grub2linux
Rank: 1
等 级:新手上路
帖 子:335
专家分:0
注 册:2004-12-25
收藏
 问题点数:0 回复次数:1 
出现一个奇怪的C问题: 高手看看,指点一下?

下面是建立,插入,删除,显示动态链表的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); }

搜索更多相关主题的帖子: include 动态 
2005-01-05 13:22
grub2linux
Rank: 1
等 级:新手上路
帖 子:335
专家分:0
注 册:2004-12-25
收藏
得分:0 
哇! 这么多! 多谢关注,
idealistic,我试试你的建议

有缘相识!我中文系的 3月拿下C/C++/VC 5天写游戏 2月写游戏系统 有空去http://mykool.go2.
2005-01-14 00:41
快速回复:出现一个奇怪的C问题: 高手看看,指点一下?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016413 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved