【问题标题】:How to insert string into linked list in c如何在c中将字符串插入到链表中
【发布时间】: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-&gt;data 未分配。此外,不要强制返回 mallocitem = malloc (sizeof *item) 很好,然后item-&gt;data = malloc ( strlen (word) + 1)(隐含* sizeof (char)

标签: c linked-list insertion-sort


【解决方案1】:
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];

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多