C语言谭浩强链表题目求解?

I_better 2014-11-24 05:42:34
谭浩强题目,对链表插入一个结点p0。按number从小到大插入。
现在问题来了。通过单步调试得知,链表的链接应该没问题。
但是输出是无限循环。实在不知错在哪儿。谢谢

#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct student)
#define NULL 0
struct student
{
int number;
struct student *next;
};

int n=0;

struct student *creat(void)
{
struct student *head,*p1,*p2;
head=NULL;
p1=p2=(struct student *)malloc(LEN);
scanf("%d",&p1->number);
while(p1->number!=0)
{
n++;
if(n==1) head=p2;
else p2->next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
scanf("%d",&p1->number);
}
p2->next=NULL;
return head;
}


struct student *cha(struct student *head,struct student p0)
{
struct student *p1=head,*p2;
if(p0.number<=p1->number)
{
head=&p0;
p0.next=p1;
return head;
}
else
while(p1->next!=NULL)
{
p2=p1;
p1=p1->next;
if(p0.number<=p1->number)
{
p2->next=&p0;
p0.next=p1;
return head;
}
}
p1->next=&p0;
p0.next=NULL;
return head;
}


void print(struct student *p)
{
if(p==NULL)
printf("0");
else
while(p!=NULL)
{
printf("%d",p->number);
p=p->next;
}

}

void main()
{
int x;
struct student *p;
p=creat();
struct student p0;
scanf("%d",&x);
p0.number=x;
p0.next=NULL;
p=cha(p,p0);
print(p);
}
...全文
97 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
I_better 2014-11-24
  • 打赏
  • 举报
回复
引用 3 楼 u010030181 的回复:
少年,不要试图去返回局部变量的地址……
struct student *cha(struct student *head,struct student* p0)
里面的相应改下,main函数中改成如下
struct student *p0 = (struct student*)malloc(sizeof(struct student));
scanf("%d",&x);
p0->number=x;
p0->next=NULL;
非常感谢!!
I_better 2014-11-24
  • 打赏
  • 举报
回复
引用 4 楼 I_better 的回复:
[quote=引用 1 楼 michael2988 的回复:] cha()函数第二个参数实际运行时只是个复本,函数结束时丢失。用指针吧
你是对的[/quote] 非常感谢!!
I_better 2014-11-24
  • 打赏
  • 举报
回复
引用 1 楼 michael2988 的回复:
cha()函数第二个参数实际运行时只是个复本,函数结束时丢失。用指针吧
你是对的
QIUSQJF 2014-11-24
  • 打赏
  • 举报
回复
少年,不要试图去返回局部变量的地址……
struct student *cha(struct student *head,struct student* p0)
里面的相应改下,main函数中改成如下
struct student *p0 = (struct student*)malloc(sizeof(struct student));
scanf("%d",&x);
p0->number=x;
p0->next=NULL;
I_better 2014-11-24
  • 打赏
  • 举报
回复
引用 1 楼 michael2988 的回复:
cha()函数第二个参数实际运行时只是个复本,函数结束时丢失。用指针吧
不是这个问题哈。。。。就是用的指针。函数结束后,链表的number是正确的。。。
michael2988 2014-11-24
  • 打赏
  • 举报
回复
cha()函数第二个参数实际运行时只是个复本,函数结束时丢失。用指针吧

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧