如何在c中向链表中插入字符串

如何在c中向链表中插入字符串,c,linked-list,insertion-sort,C,Linked List,Insertion Sort,我想写一个可以按字母顺序插入字符串的函数。 可声明为: typedef struct Node Node; typedef struct Node { char *data; Node *next; }; Node *insertion(Node *head,char *arr); 如何定义此函数 我的代码 #include <stdio.h> #include <stdlib.h> #include <string.h> typedef

我想写一个可以按字母顺序插入字符串的函数。 可声明为:

typedef struct Node Node;
typedef struct Node
{
    char *data;
    Node *next;
};

Node *insertion(Node *head,char *arr);
如何定义此函数

我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node Node;
typedef struct Node
{
    char *data;
    Node *next;
};
Node *MyList = 0;
void AddWord(char *word) // Add a new word to the list MyList
    { Node *item,*next;
    item = (Node *) malloc(sizeof(Node));
    if ( item==0 ) { printf ("Malloc Failed \n");  return ; }
    strcpy(item->data,word); // Copy Word into new Item
    item->next = 0; // Set that next Item is nothing

    if ( MyList == 0 ) // If List is Empty, make this the first item
        { MyList = item; return ; }

    if(strcmp(word,MyList->data) < 0 ) // Check if the new item comes before the first item in old list
        { item->next = MyList; MyList = item; return ; }

    // Check to see if an item is inserted before the next item
    for ( next = MyList ; next ->next != 0 ; next = next ->next )
        {
        if (strcmp (word, next->next->data) < 0 )
            { // Insert Item before the next Item.
            item ->next = next->next;
            next->next = item ; return;
            }
        }

    // There are no more items ! Add to end
    next ->next = item;
    }
#包括
#包括
#包括
typedef结构节点;
定义表结点
{
字符*数据;
节点*下一步;
};
节点*MyList=0;
void AddWord(char*word)//在列表MyList中添加一个新词
{节点*项,*下一步;
项目=(节点*)malloc(节点大小);
if(item==0){printf(“Malloc失败\n”);return;}
strcpy(项目->数据,word);//将word复制到新项目中
item->next=0;//设置下一项为空
if(MyList==0)//如果列表为空,则将其作为第一项
{MyList=item;return;}
if(strcmp(word,MyList->data)<0)//检查新项是否位于旧列表中的第一项之前
{item->next=MyList;MyList=item;return;}
//检查项目是否在下一个项目之前插入
for(next=MyList;next->next!=0;next=next->next)
{
if(strcmp(字,下一个->下一个->数据)<0)
{//在下一项之前插入项。
项目->下一步=下一步->下一步;
下一步->下一步=项目;返回;
}
}
//没有其他项目!添加到结尾
下一步->下一步=项目;
}
项->数据是未初始化的指针。您应该分配要复制到的空间,或者在节点结构中将数据声明为数组:


字符数据[某些大小]

虽然对输入进行排序以创建有序列表是可以的,但是要知道,没有办法恢复原始顺序。例如,如果您正在读取一个文本文件,则按insert排序会产生有趣的读取效果。为了保持列表中的灵活性,请考虑在本地顺序中插入,为列表编写排序函数。上面的
项->数据
未分配。此外,不要强制转换
malloc
的返回值
item=malloc(sizeof*item)
可以,然后
item->data=malloc(strlen(word)+1)
(暗含
*sizeof(char)
item = (Node *) malloc(sizeof(Node));
if ( item==0 ) { printf ("Malloc Failed \n");  return ; }
strcpy(item->data,word); // Copy Word into new Item