[英]How can return a pointer pointing to the largest value in a linked list?
This is my attempt 这是我的尝试
// Return a pointer to node with the largest value.
// You may assume list has at least one element
Node * pointerToMax(LinkedList *list) {
assert(list!=NULL);
assert(list->head != NULL);
Node *p, *q;
p = list->head;
q = list->head;
int max = q->data;
while(p != NULL){
if(p->data > max){
max = p->data;
}
return p;
p = p->next;
}
}
Here are the struct definitions. 这是结构定义。
struct Node {
int data;
Node *next;
};
struct LinkedList {
Node *head;
Node *tail;
};
I'm trying to figure out how to return a pointer that points to the largest value, but I can't exactly figure out how to return the pointer to variable max
, and I'm not even sure if the max
variable is being updated correctly. 我试图弄清楚如何返回一个指向最大值的指针,但是我不能确切地弄清楚如何将指针返回给变量
max
,我甚至不确定max
变量是否正在更新。正确地。
You want something like this: 您想要这样的东西:
Node *maxNode = p;
int max = p->data;
while(p != NULL){
if(p->data > max){
max = p->data;
maxNode = p;
}
p = p->next;
}
return maxNode;
There is no reason to return
in your while loop. 没有理由在while循环中
return
。 We don't know what the max Node
is until we've looped through all the nodes. 我们不知道是什么最大
Node
是,直到我们完成了所有的节点循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.