链表插入死循环
#include <stdio.h>#include <stdlib.h>
#include <malloc.h>
#define LEN sizeof(struct student)//student结构体的大小
structstudent *creat();
int n;
void print(struct student *head);
structstudent *insert(struct student *head);
struct student
{
int num;
float score;
struct student *next;
};
int main()
{
struct student*stu;
stu = creat();
print(stu);
print(insert(stu));
return 0;
}
structstudent *creat()
{
struct student *head;
struct student *p1, *p2;
p1 = p2 = (struct student*)malloc(LEN);
printf("Enter the num:");
scanf("%d", &p1->num);
printf("Enter the score:");
scanf("%f", &p1->score);
head = NULL;
n = 0;
while(p1->num!=0)
{
n++;
if(n==1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (struct student*)malloc(LEN);
printf("Enter the num:");
scanf("%d", &p1->num);
printf("Enter the score:");
scanf("%f", &p1->score);
}
p2->next = NULL;
return head;
}
void print(struct student *head)
{
struct student *p;
p = head;
while(p!=NULL)
{
printf("%d\n", p->num);
printf("%f\n", p->score);
p = p->next;
}
}
structstudent *insert(struct student *head)
{
struct student *p1, *p2, *p3;
p1 = head;
printf("Please enter the num to insert:");
scanf("%d", &p3->num);
printf("Please enter the score to insert:");
scanf("%f", &p3->score);
if(head == NULL)
{
head = p3;
p3->next = NULL;
}
while((p3->num > p1->num)&&(p1!=NULL))
{
p2 = p1;
p1 = p1->next;
}
if(p3->num<=p1->num)
{
if(p1->next ==NULL)
{
head = p3;
p3->next = p1;
}
else
{
p2->next = p3;
p3->next = p1;
}
}
else
{
p1->next = p3;
p3->next = NULL;
}
return head;
}
大佬们帮我看看, 我的插入都是死循环,麻烦大佬们提示提示小弟,谢谢大哥~{:10_257:} insert() 函数里应该先为指针分配内存然后再使用。 jackz007 发表于 2019-5-27 07:41
insert() 函数里应该先为指针分配内存然后再使用。
问题得到解决,谢谢大佬{:5_109:} insert()函数怎样为指针分配内存
页:
[1]