将字符串插入到C中已排序的字符串链表中



我正在努力解决这个问题:我想把一个字符串插入到一个排序的字符串链表中,但由于某种原因,它不起作用。这是代码:

void insert(node** head, const char* word){
node* newElem = malloc(sizeof(node));
newElem->data = malloc(sizeof (char)*(wordLenght+1));
strcpy(newElem->data, word);
if (*head == NULL || strcmp(newElem->data, (*head)->data) < 0){
newElem->next = *head;
*head = newElem;
return;
}
nodo* cursor = *head;
while (cursor->next != NULL && strcmp(newElem->data, cursor->data) < 0){
cursor = cursor->next;
}
newElem->next = cursor->next;
cursor->next = newElem;
}

我试过这套字符串

7DJL,-kiF, 8F4r, 7D7d, -D7w, -b7f

但没用。输出应为:

-D7w, -b7f, -kiF, 7D7d, 7DJL, 8F4r

谢谢你的帮助!

我不知道什么是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

最新更新