C++中数组的链接列表 [英] linked list of arrays in c

查看:0
本文介绍了C++中数组的链接列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将数组指定为链表元素时遇到问题。我试着把字符改成字符*但对我没有帮助。我真的很感激你的名字 在这里我创建了一个结构

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)

推荐答案

只需重新声明结构即可,如

#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] = '';
        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;
}

这篇关于C++中数组的链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆