读书人

初学者!删除链表节点时报错

发布时间: 2012-08-03 00:12:14 作者: rapoo

菜鸟求助!!删除链表节点时报错~
#include <stdio.h> //链表的建立和输出
#include <malloc.h>
#define NULL 0
#define LEN sizeof(struct student)
int n;
struct student
{
long num;
float score;
struct student *next;
};

struct student *creat(void) //链表的建立
{
struct student *head;
struct student *p1,*p2;
n=0;
p1=p2=(struct student *)malloc(LEN);
scanf("%ld,%f",&p1->num,&p2->score);
head=NULL;
while(p1->num!=0)
{
n++;
if(n==1)
{
head=p1;
}
else
p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%ld,%f",&p1->num,&p1->score);
}
p2->next=NULL;
return(head);
}

void print(struct student *point) //链表的输出
{
if(point!=NULL)
{
do
{
printf("编号:%d 成绩:%5.1f\n",point->num,point->score);
point=point->next;
}
while(point!=NULL);
}
}

struct student *del(struct student *head,long num)//删除节点
{
struct student *p1,*p2;
if(head=NULL)
{
printf("\nlist null!\n");
goto end;
}
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;
printf("delete:%ld",num);
n=n-1;
}
else
printf("%ld not found!\n",num);
end:;
return(head);
}


void main()
{
struct student *p;
p=creat(); //建立链表
print(p); //输出链表
p=del(p,2); //删除节点2
print(p); //输出链表
for(;;);
}

删除节点时出错,提示:Access Violation。
哪位好心人帮忙看看~~~~
我用的VC6

[解决办法]

C/C++ code
#include <stdio.h> //链表的建立和输出#include <malloc.h>#define NULL 0#define LEN sizeof(struct student)int n;struct student{    long num;    float score;    struct student *next;};struct student *creat(void) //链表的建立{    struct student *head;    struct student *p1,*p2;    n=0;    p1=p2=(struct student *)malloc(LEN);    scanf("%ld,%f",&p1->num,&p2->score);    head=NULL;    while(p1->num!=0)    {        n++;        if(n==1)        {            head=p1;        }        else            p2->next=p1;        p2=p1;        p1=(struct student *)malloc(LEN);        scanf("%ld,%f",&p1->num,&p1->score);    }    p2->next=NULL;    return(head);}void print(struct student *point) //链表的输出{    if(point!=NULL)    {        struct student *pt = point;        do        {            printf("编号:%d 成绩:%5.1f\n",pt->num,pt->score);            pt=pt->next;        }        while(pt!=NULL);    }}struct student *del(struct student *head,long num)//删除节点{    struct student *p1,*p2;    if(head==NULL)    {        printf("\nlist null!\n");        goto end;    }    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;        printf("delete:%ld",num);        n=n-1;    }    else        printf("%ld not found!\n",num);end:;    return(head);}void main(){    struct student *p;    p=creat(); //建立链表    print(p); //输出链表    p=del(p,2); //删除节点2    print(p); //输出链表    for(;;);} 

读书人网 >C语言

热点推荐