C 如何从链表中找到最大元素?
这就是我迄今为止所尝试的C 如何从链表中找到最大元素?,c,linked-list,C,Linked List,这就是我迄今为止所尝试的 #include<stdlib.h> struct node { int data; struct node *next; }; void create(struct node **q) { struct node *r,*t; int cnt,i,dat; printf("How many nodes?"); scanf("%d",&cnt); for(i=0;i<cnt;i++) { p
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void create(struct node **q)
{
struct node *r,*t;
int cnt,i,dat;
printf("How many nodes?");
scanf("%d",&cnt);
for(i=0;i<cnt;i++)
{
printf("Enter the data %d ",i);
scanf("%d",&dat);
r=(struct node *) malloc (sizeof(struct node));
r->data=dat;
r->next=NULL;
if(*q==NULL)
{
*q=r;
}
else
{
t=*q;
while(t->next!=NULL)
{
t=t->next;
}
t->next=r;
}
}
}
void display(struct node **q)
{
struct node *r;
r=*q;
while(r!=NULL)
{
printf("%d->",r->data);
r=r->next;
}
printf("\n");
}
void max(struct node **q)
{
struct node *r;
int max=0;
r=*q;
while((r->next)!=NULL)
{
max=r->data;
r=r->next;
if((r->data)>max)
{
max=r->data;
}
}
printf("The max is %d",max);
printf("\n");
}
int main()
{
struct node *head;
create(&head);
display(&head);
max(&head);
}
循环中存在一些问题
while((r->next)!=NULL) {
max=r->data;
r=r->next;
if((r->data)>max) {
max=r->data;
}
}
行max=r->data
无条件更新max
。再加上测试(r->next)=NULL
导致循环提前退出一项,循环当前始终返回最后一项的值
代码应该更改为
while(r!=NULL) {
if(r->data>max) {
max=r->data;
}
r=r->next;
}
你的输入,3 2 1,意味着你给cnt 3,然后2和1作为链接的成员?这位工人…非常感谢…我是C新手,感谢你的帮助..你能给我推荐一些好的数据结构网站吗?很高兴它有帮助。对于yo来说,接下来要做的最好的事情就是学习如何使用调试器。如果您能够逐步完成代码,您可能已经注意到/自己解决了这些问题。再次感谢您的精彩技巧。我很高兴你很高兴你的解决方案成功了…我来看看调试技术..谢谢你
while(r!=NULL) {
if(r->data>max) {
max=r->data;
}
r=r->next;
}