|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Student
{
int num;
int score;
struct Student *next;
};
#define LEN sizeof(struct Student)
struct Student *create(); //创建链表的函数
struct Student *del(struct Student *stu,int num); //删除函数
void printStudent(struct Student *stu); //打印数据的函数
int n;
void main()
{
struct Student *stu,*p; //定义一个指针接收head
int a;
stu=create();
p=stu;
printStudent(p);
printf("input delete num:");
scanf("%d",&a);
printStudent(del(p,a));
}
struct Student *create()
{
struct Student *p1,*p2,*head;
p1=p2=(struct Student *)malloc(LEN); //p1p2分配空间
printf("please input student number:");
scanf("%d",&p1->num);
printf("please input the student score:");
scanf("%d",&p1->score);
n=0; //初始化n的值
head=NULL; //初始化head的值
while(p1->num)
{
n++;
if(n==1){
head=p1; //head指向第一个结构
}
else{
p2->next=p1; //前一个链接到后一个
}
p2=p1; //p2变成原本p1的值
//p1开辟新的空间(结构)
p1=(struct Student *)malloc(LEN);
printf("please input student number:");
scanf("%d",&p1->num);
printf("please input the student score:");
scanf("%d",&p1->score);
}
return head; //返回头指针
}
void printStudent(struct Student *stu) //打印数据
{
struct Student *p;
p=stu;
do
{
printf("number:%d\n",p->num);
printf("score:%d\n\n",p->score);
p=p->next;
}while(p->num);
}
struct Student *del(struct Student *stu,int num)
{
struct Student *p1,*p2;
if(stu == NULL)
{
printf("这是个空指针");
goto END;
}
p1 = stu;
while(p1->num != num && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if(num == p1->num)
{
if(p1 == stu)
{
stu = p1->next;
}
else
{
p2->next=p1->next;
}
printf("\ndelete num:%d succeed\n",num);
n=n-1;
}
else
{
printf("%d not been found!\n",num);
}
END:
return stu;
}
我发现
问题一:
个人感觉看不懂的是从create开始的,如果num不等于0,你怎么让这个创建结束呢?
如果第一个创建的num为0,你的head根本就没有 head=p1; 就直接return head,导致后面直接返回的指针其实为null,那么你再用指针必然报错
问题二:
- if(n==1){
- head=p1; //head指向第一个结构
- }
- else{
- p2->next=p1; //前一个链接到后一个
- }
- p2=p1; //p2变成原本p1的值
复制代码
这个逻辑我有点看不明白
head=p1
那么head->next=什么?
然后 p2->next=p1; 接着p2=p1,新的p2也就是p1->next是什么呢?
个人觉得,是你create的问题导致了后面的问题,建议在create断点,看看你的p1、p2还有head到底怎么回事
|
|