由网友(丶那男人的谎言)分享简介:我在将数组指定为链表元素时遇到问题。我试着把字符改成字符*但对我没有帮助。我真的很感激你的名字在这里我创建了一个结构struct node{char data;struct node *next;};并添加了此函数以添加新节点void addLast(struct node **head, char val...![社招面试题 常见 14 种算法解题模式 套模板都能拿高薪](https://p.xsw88.cn/allimgs/daicuo/20230903/2749.png)
我在将数组指定为链表元素时遇到问题。我试着把字符改成字符*但对我没有帮助。我真的很感激你的名字 在这里我创建了一个结构
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;
}
}
![社招面试题 常见 14 种算法解题模式 套模板都能拿高薪](https://p.xsw88.cn/allimgs/daicuo/20230903/2749.png)
这就是如何将数据传递给函数
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;
}
相关推荐
最新文章