gpt4 book ai didi

c++ - 如何返回指向链表中最大值的指针?

转载 作者:行者123 更新时间:2023-11-30 01:08:27 26 4
gpt4 key购买 nike

这是我的尝试

// 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;
}
}

这是结构定义。

struct Node {
int data;
Node *next;
};

struct LinkedList {
Node *head;
Node *tail;
};

我试图弄清楚如何返回一个指向最大值的指针,但我无法确切地弄清楚如何返回指向变量 max 的指针,而且我是甚至不确定 max 变量是否被正确更新。

最佳答案

你想要这样的东西:

Node *maxNode = p;
int max = p->data;
while(p != NULL){
if(p->data > max){
max = p->data;
maxNode = p;
}
p = p->next;
}
return maxNode;

没有理由在 while 循环中return。在遍历所有节点之前,我们不知道最大Node是多少。

关于c++ - 如何返回指向链表中最大值的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com