链表插入过程正确,打印输出时发生错误
#include<stdio.h>#include<malloc.h>
#include<stdlib.h>
#define LENsizeof(struct student)//student结构的大小
struct student *creat();//创建链表
struct student *del(struct student *head,int num);//del函数用于删除节点 *head为删除链表的头结点num为删除节点的num
struct student *insert(struct student *head,struct student stu_2); //给链表中插入节点
void print(struct student *head); //打印链表
struct student
{
int num;
float score;
struct student *next;
};
int n; //全局变量,用来纪录存放了多少数据
void main()
{
struct student *stu,*p,stu_1;
int n;
stu=creat();
p=stu;
print(p);
/*
printf("please enter the num to delete:");
scanf("%d",&n);
print(del(p,n));
*/
printf("please insert new num:");
scanf("%d",&stu_1.num);
printf("please insert new score:");
scanf("%f",&stu_1.score);
print(insert(stu, stu_1));
printf("\n\n");
system("pause");
}
struct student *creat()
{
struct student *head;
struct student *p1,*p2;
int n=0;
p1=p2=(struct student *)malloc(LEN); //LEN 是student 结构的大小
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
head=NULL;
while(p1->num!=0)
{
n=n+1;
if(n==1)
{
head=p1;
}
else
{
p2->next=p1;
}
p2=p1;
p1=(struct student *)malloc(LEN);
printf("please enter the num:");
scanf("%d",&p1->num);
printf("please enter the score:");
scanf("%f",&p1->score);
}
p2->next=NULL;
return head;
}
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
if(head==NULL)
return head;
else
{
p1=head;
while(p1->num!=num&& p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(p1->num==num)
{
if(p1==head)
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
}
else
{
printf("lt's have been find it\n");
}
return head;
}
}
struct student *insert(struct student *head,struct student stu_2)
{
struct student *p1,*p0,*p2;
p1=head;
p0=&stu_2;
if(head!=NULL)
{
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;
}
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
else
{
head=p0;
p0->next=NULL;
}
return head;
}
void print(struct student *head)
{
struct student *p;
p=head;
if(head!=NULL)
{
do
{
printf("num %d\t score%f\t\n",p->num,p->score);
p=p->next;
}
while(p!=NULL);
}
else
printf("The list is null!");
}
打印输出时发生错误??? cplus 发表于 2019-8-25 19:25
打印输出时发生错误???
对无限的重复
大佬求帮助?? 检查你的 insert 函数 struct student * insert(struct student *head, struct student * stu_2)
值传递,和引用传递有区别
还有变量写成p1 p2 有意思吗? 结构体支持值传递 注意使用 本帖最后由 superbe 于 2019-8-26 21:10 编辑
楼上説得对,就是insert函数和传参的问题,把四行改成这样:
......
struct student *insert(struct student *head,struct student* stu_2); //1. insert函数的声明
......
void main(){
......
print(insert(stu, &stu_1)); //2. 调用insert函数
.......
}
......
struct student *insert(struct student *head,struct student* stu_2) //3. insert函数定义
{
struct student *p1,*p0,*p2;
p1=head;
p0=stu_2; //4. 这行去掉了&
......
如果用C++(把扩展名改成.cpp),只需要在1、3两行中stu_2前面加上&就可以了。
页:
[1]