我正在尝试在C中创建字符串的链接列表,并且在将第一个节点添加到列表中时遇到了问题 . 无论出于何种原因,我的程序打印NULL,即使我将head变量引用到newNode但它不会将字符串从struct指针复制到struct指针 . 任何帮助表示赞赏 . 谢谢!
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
typedef struct stringData {
char *s;
struct stringData *next;
} Node;
Node *createNode(char *s) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->s = s;
newNode->next = NULL;
return newNode;
}
void insert(Node *head, Node *newNode) {
if (head == NULL) {
head->s = newNode->s;
head = newNode;
}
}
void printList(Node *head) {
while (head != NULL) {
printf("%s\n", head->s);
head = head->next;
}
}
int main()
{
Node *head = createNode(NULL);
Node *a = createNode("A");
insert(head, a);
printList(head);
return 0;
}
2 回答
以下代码段错误:
您需要通过引用传递指针 . 目前您正在更改本地副本(参数) .
Fix
将您的
insert
更改为:并致电:
What else
Atleast
insert
(可能)更多的功能不是万无一失的(保证空指针取消引用,else
未处理的情况等) . 您需要调试并修复许多此类情况 . 在编码之前在纸上正确使用您的方法可能有所帮助以下是代码的修改版本,它给出了在列表开头和列表末尾插入新节点的示例 . 实际上,
insert
函数可用于在列表中的任何位置插入新节点,因为它只需要指向链接的指针和指向要插入的节点的指针 .