C语言求链表中数据的最大值的问题
我写了一个程序如下#include<stdio.h>#include<stdlib.h>structNum{intnum;structNum*next;};structN...
我写了一个程序如下
#include <stdio.h>
#include <stdlib.h>
struct Num
{
int num;
struct Num *next;
};
struct Num *create() //建立链表
{
struct Num *head,*tail,*p;
head = tail = NULL;
while(1)
{
p = (struct Num *)malloc(sizeof(struct Num));
scanf_s("%d",&p->num);
if(p->num == -1)
{
tail->next = NULL;
free(p);
break;
}
if(head == NULL)
head = p;
else
tail->next = p;
tail = p;
}
return head;
}
int Max(struct Num *head) //求链表最大值
{
struct Num *p;
int mx = 0;
p = head;
mx = p->num;
while(1)
{
if(p == NULL)
break;
else
{
p = p->next;
if(p->num > mx)
mx = p->num;
}
}
return mx;
}
int main()
{
struct Num *head,*p;
int m;
printf("请输入整数,输入-1结束\n");
head = create();
p = head;
printf("整数串是\n");
while(p != NULL)
{
printf("%d",p->num);
printf("\t");
p = p->next;
}
m = Max(head);
printf("最大值为%d\n",m);
system("pause");
return 0;
}
如果不使用Max函数可以正常运行,但是加入Max函数就会报错...
求解 展开
#include <stdio.h>
#include <stdlib.h>
struct Num
{
int num;
struct Num *next;
};
struct Num *create() //建立链表
{
struct Num *head,*tail,*p;
head = tail = NULL;
while(1)
{
p = (struct Num *)malloc(sizeof(struct Num));
scanf_s("%d",&p->num);
if(p->num == -1)
{
tail->next = NULL;
free(p);
break;
}
if(head == NULL)
head = p;
else
tail->next = p;
tail = p;
}
return head;
}
int Max(struct Num *head) //求链表最大值
{
struct Num *p;
int mx = 0;
p = head;
mx = p->num;
while(1)
{
if(p == NULL)
break;
else
{
p = p->next;
if(p->num > mx)
mx = p->num;
}
}
return mx;
}
int main()
{
struct Num *head,*p;
int m;
printf("请输入整数,输入-1结束\n");
head = create();
p = head;
printf("整数串是\n");
while(p != NULL)
{
printf("%d",p->num);
printf("\t");
p = p->next;
}
m = Max(head);
printf("最大值为%d\n",m);
system("pause");
return 0;
}
如果不使用Max函数可以正常运行,但是加入Max函数就会报错...
求解 展开
1个回答
展开全部
while(1)
{
if(p == NULL)
break;
else
{
p = p->next; //如果p->next=NULL,以下就错了
if(p->num > mx)
mx = p->num;
}
}
改成
while(1)
{
if(p->num > mx)
mx = p->num;
p=p->next;
if(p == NULL)
break;
}
你访问越界了
{
if(p == NULL)
break;
else
{
p = p->next; //如果p->next=NULL,以下就错了
if(p->num > mx)
mx = p->num;
}
}
改成
while(1)
{
if(p->num > mx)
mx = p->num;
p=p->next;
if(p == NULL)
break;
}
你访问越界了
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询