【发布时间】:2015-05-30 22:58:58
【问题描述】:
我想写一个可以按字母顺序插入字符串的函数。 可以声明为;
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;
}
【问题讨论】:
-
虽然对输入进行排序以创建有序列表很好,但请注意,无法取回原始订单。例如,如果您正在阅读文本文件,则在插入时排序会产生有趣的阅读效果。为了保持列表的灵活性,请考虑按本机顺序插入,为列表编写排序函数。以上
item->data未分配。此外,不要强制返回malloc。item = malloc (sizeof *item)很好,然后item->data = malloc ( strlen (word) + 1)(隐含* sizeof (char))
标签: c linked-list insertion-sort