c中数组的链表

linked list of arrays in c

我在将数组分配为链表元素时遇到问题。我试过将 char 更改为 char* 但它对我没有帮助。我真的很感激你的名字 我在这里创建了一个结构

struct node{
char data;
struct node *next;
};

并添加了此功能以添加新节点

void addLast(struct node **head, char val)
{
//create a new node
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = val;
newNode->next     = NULL;

//if head is NULL, it is an empty list
if(*head == NULL)
     *head = newNode;
//Otherwise, find the last node and add the newNode
else
{
    struct node *lastNode = *head;

    //last node's next address will be NULL.
    while(lastNode->next != NULL)
    {
        lastNode = lastNode->next;
    }

    //add the newNode at the end of the linked list
    lastNode->next = newNode;
}

}

这是将数据传递给函数的方法

int main()
{
 struct node *head = NULL;
 char name[10];

 printf("Enter book title : ");
 scanf("%s",&name);
 addLast(&head,name);
 break;
  
 return 0;
}

这是我得到的错误

error: invalid conversion from 'char*' to 'char' [-fpermissive]
  |             addLast(&head,name);
  |                           ^~~~
  |                           |
  |                           char*
note:   initializing argument 2 of 'void addLast(node**, char)'
void addLast(struct node **head, char val)

为了存储书名,您需要为整个书名保留 space,而不仅仅是一个字母

改变

struct node{
char data;
struct node *next;
};

struct node{
char* data;
struct node *next;
};

现在读取名称时,在新节点中为文本分配内存

void addLast(struct node **head, char* val)
{
//create a new node
int len = strlen(val);
struct node *newNode = malloc(sizeof(struct node));
newNode->data = malloc(len+1); // text length + ending [=12=]
// copy text
strcpy_s(newNode->data, len+1, val );
newNode->next     = NULL; 

其他一些观察结果

保留指向最后一个元素的指针,这样可以加快追加速度。 10(9) 个字符对于书名来说可能有点小

一样重新声明结构
#include <strio.h>
#include <stdlib.h>
#include <string.h>

//...

#define  NAME_LENGTH 10

struct node{
    char name[NAME_LENGTH];
    struct node *next;
};

在这种情况下,函数看起来像

int addLast( struct node **head, const char *name )
{
    //create a new node
    struct node *newNode = malloc( sizeof( struct node ) );
    int success = newNode != NULL;

    if ( success )
    {
        strncpy( newNode->name, name, NAME_LENGTH );
        newNode->name[NAME_LENGTH - 1] = '[=11=]';
        newNode->next = NULL;

        //if head is NULL, it is an empty list
        if ( *head == NULL )
        {
            *head = newNode;
        }
        //Otherwise, find the last node and add the newNode
        else
        {
            struct node *lastNode = *head;

            //last node's next address will be NULL.
            while ( lastNode->next != NULL )
            {
                lastNode = lastNode->next;
            }

            //add the newNode at the end of the linked list
            lastNode->next = newNode;
        }
    }

    return success;
}