我试图返回包含具有最大值的项目的第一个节点。这是我的代码,
struct ListNode* CreateNode(int item) {
struct ListNode* Newnode = (struct
ListNode*)malloc(sizeof(struct ListNode)); //allocate new node
Newnode->item = item;
Newnode->next = NULL;
return Newnode;}
struct ListNode* searchmaxvalNode (struct ListNode *head) {
struct ListNode *cur = head;
int max = head->item;
while(cur != NULL){
if((cur->item) < max){
max = cur->item;
}
cur = cur->next;
return cur;
}
return NULL;
}
struct ListNode { //list.h file
int item;
struct ListNode *next;
};
我的searchmaxvalnode函数有什么问题?
一般来说,指针head
可以等于NULL。所以你的函数可以调用未定义的行为,因为它会尝试使用空指针访问内存。
还有if语句
if((cur->item) < max){
max = cur->item;
}
是不正确的,没有意义。实际上,它选择了一个最小值。
还有这个返回语句
return cur;
至少应该放在while循环之外,尽管它也没有意义,因为它返回的是指向当前节点的指针,而不是指向值最大的节点的指针。
函数可以如下所示:
struct ListNode * searchmaxvalNode ( struct ListNode *head )
{
struct ListNode *max = head;
if ( head != NULL )
{
while ( ( head = head->next ) != NULL )
{
if ( max->item < head->item ) max = head;
}
}
return max;
}
这是一个示范程序。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct ListNode
{
int item;
struct ListNode *next;
};
struct ListNode * CreateNode( int item )
{
struct ListNode *Newnode = malloc( sizeof( struct ListNode ) );
if ( Newnode != NULL )
{
Newnode->item = item;
Newnode->next = NULL;
}
return Newnode;
}
int push_front( struct ListNode **head, int item )
{
struct ListNode *Newnode = CreateNode( item );
int success = Newnode != NULL;
if ( success )
{
Newnode->next = *head;
*head = Newnode;
}
return success;
}
void display( const struct ListNode *head )
{
for ( ; head != NULL; head = head->next )
{
printf( "%d -> ", head->item );
}
puts( "null" );
}
struct ListNode * searchmaxvalNode( struct ListNode *head )
{
struct ListNode *max = head;
if ( head != NULL )
{
while ( ( head = head->next ) != NULL )
{
if ( max->item < head->item ) max = head;
}
}
return max;
}
int main(void)
{
struct ListNode *head = NULL;
srand( ( unsigned int )time( NULL ) );
const int N = 10;
for ( int i = 0; i < N; i++ )
{
push_front( &head, rand() % N );
}
display( head );
struct ListNode *max = searchmaxvalNode( head );
printf( "The maximum value stored in the list is %dn", max->item );
return 0;
}
程序输出为
1 -> 8 -> 2 -> 1 -> 4 -> 6 -> 4 -> 5 -> 8 -> 4 -> null
The maximum value stored in the list is 8