我想写一个函数,可以按字母顺序插入字符串。可以声明为;
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 = (Node *) malloc(sizeof(Node));
if ( item==0 ) { printf ("Malloc Failed n"); return ; }
strcpy(item->data,word); // Copy Word into new Item
item->data是非初始化指针。您应该分配空间进行复制,或者在Node结构中将数据声明为数组:
字符数据(someSize);