我不知道wordLenght
是什么.但在任何情况下,在函数中使用此名称都没有意义,只会使函数变得不清楚,因为该名称没有在函数中定义.
不需要将函数分成两部分.这使得函数容易出错.
此外,While语句的条件
while (cursor->next != NULL && strcmp(newElem->data, cursor->data) < 0){
是不正确的.
如果此表达式
strcmp(newElem->data, cursor->data) < 0
计算结果为True,则需要中断循环.
还有一个打字错误
nodo* cursor = *head;
看来你的意思是
node* cursor = *head;
该函数可能如下所示
int insert( node** head, const char* word )
{
node *newElem = malloc( sizeof( node ) );
int success = newElem != NULL;
if ( success )
{
success = ( newElem->data = malloc( strlen( word ) + 1 ) ) != NULL;
if ( success )
{
strcpy( newElem->data, word );
while ( *head != NULL && !( strcmp( word, ( *head )->data ) < 0 ) )
{
head = &( *head )->next;
}
newElem->next = *head;
*head = newElem;
}
else
{
free( newElem );
}
}
return success;
}
这是一个演示程序.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char *data;
struct node *next;
} node;
int insert( node** head, const char* word )
{
node *newElem = malloc( sizeof( node ) );
int success = newElem != NULL;
if ( success )
{
success = ( newElem->data = malloc( strlen( word ) + 1 ) ) != NULL;
if ( success )
{
strcpy( newElem->data, word );
while ( *head != NULL && !( strcmp( word, ( *head )->data ) < 0 ) )
{
head = &( *head )->next;
}
newElem->next = *head;
*head = newElem;
}
else
{
free( newElem );
}
}
return success;
}
void display( const node *head )
{
for ( ; head; head = head->next )
{
printf( "\"%s\" -> ", head->data );
}
puts( "null" );
}
int main (void)
{
node *head = NULL;
const char * data[] =
{
"7DJL", "-kiF", "8F4r", "7D7d", "-D7w", "-b7f"
};
const size_t N = sizeof( data ) / sizeof( *data );
for ( size_t i = 0; i < N; i++ )
{
insert( &head, data[i] );
}
display( head );
}
程序输出为
"-D7w" -> "-b7f" -> "-kiF" -> "7D7d" -> "7DJL" -> "8F4r" -> null