本人菜鸟,最近做到拆分单链表的时候,发现只能读取首节点的信息,之后next就会变成null,代码如下
真的找不到错误了。。希望大神们帮帮忙
#include "stdio.h"
#include "stdlib.h"
#define LEN sizeof(struct student)
struct student
{
int num;
char name[8];
char sex[2];
int age;
struct student *next;
}stu[10];
int co(struct student *pa,int length)
{
struct student *pd = NULL,*pe = NULL,*pb = NULL,*pc = NULL;
int i;
for(i=0;i<length;i++)
{
printf("...");
pb=(struct student *)malloc(LEN);
pc=(struct student *)malloc(LEN);
if(pa->num>=80)
{
if (i==0) {
pb=pd=pa;
pb->next=NULL;
}
else
{
pb=pa;
pd->next=pb;
pb->next=NULL;
}
}
else
{
if (i==0) {
pc=pe=pa;
pc->next=NULL;
}
else
{
pc=pa;
pe->next=pc;
pc->next=NULL;
}
}
pa=pa->next;
}
printf(">80: %d %s %s %d\n",pb->num,pb->name,pb->sex,pb->age);
printf("other: %d %s %s %d\n",pc->num,pc->name,pc->sex,pc->age);
return 0;
}
int main()
{
struct student *p,*pt = NULL,*head = NULL;
int i,length = 0,inum,flag=1;
int find=0;
while (flag==1) {
printf("input length\n:");
scanf("%d",&length);
if(length<10)
flag=0;
}
for(i=0;i<length;i++)
{
p=(struct student *)malloc(LEN);
if (i==0)
head=pt=p;
else
pt->next=p;
pt=p;
printf("please input the num:\n");
scanf("%d",&p->num);
printf("please input the name:\n");
scanf("%s",p->name);
printf("please input the sex:\n");
scanf("%s",p->sex);
printf("please input the age:\n");
scanf("%d",&p->age);
p->next=NULL;
}
p=head;
while(p!=NULL)
{
printf("%d %s %s %d\n",p->num,p->name,p->sex,p->age);
p=p->next;
}
printf("please input the num:\n");
scanf("%d",&inum);
pt=head;
p=pt;
if(inum==p->num)
{
p=p->next;
pt=head=p;
find=1;
}
else
p=p->next;
while (p!=NULL) {
if(p->num==inum)
{
pt->next=p->next;
find=1;
}
else
{
pt=p;
p=pt->next;
}
if(!find)
printf("no find\n");
else
printf("have delete\n");
p=head;
while (p!=0) {
printf("%d %s %s %d\n",p->num,p->name,p->sex,p->age);
p=p->next;
}
}
p=head;
co(p,length);
return 0;
}
输入信息如下,
input length
:3
please input the num:
99
please input the name:
cc
please input the sex:
man
please input the age:
23
please input the num:
74
please input the name:
bb
please input the sex:
man
please input the age:
44
please input the num:
23
please input the name:
aa
please input the sex:
man
please input the age:
33
99 cc man 23
74 bb man 44
23 aa man 33
please input the num:
74
have delete
99 cc man 23
23 aa man 33
......(lldb)
报错信息如下:
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
