如何计算并返回指向max元素的指针的值?C++

How do I calculate and return the value of pointer to max element? C++

本文关键字:元素 max 指针 C++ 何计算 计算 返回      更新时间:2023-10-16

我在这个问题上遇到了极大的困难。这是我编码的,但它不起作用。这些是说明书。待办事项:在此处插入代码进行计算并返回指向最大元素的指针值(如果平局,则为第一个)

Node * pointerToMax(LinkedList *list) {
assert(list!=NULL);
assert(list->head != NULL);
Node *max = list->head;
for (list->head=list->head; list!=NULL; list->head=list->head->next){
    if (list->head->next > max){
        max = list->head->next;
    }
}
return max;
}

让我们假设节点是由其数据成员data进行比较的(或者由数据成员value或其他数据成员进行比较,您没有显示节点必须如何进行比较)。然后代码可以看起来像

Node * pointerToMax( LinkedList *list ) 
{
    //assert(list!=NULL);
    //assert(list->head != NULL);
    if ( list == NULL || list->head == NULL ) return NULL;
    Node *max = list->head;
    for ( Node *node = list->head->next; node !=NULL; node = node->next )
    {
        if ( max->data < node->data ) max = node;
    }
    return max;
}

如果Node类定义了用于比较节点的operator <,那么您应该替换语句

        if ( max->data < node->data ) max = node;

对于

        if ( *max < *node ) max = node;