【发布时间】:2016-07-23 12:49:54
【问题描述】:
我正在尝试在 C 中创建一个字符串链接列表,但在将第一个节点添加到列表中时遇到了问题。无论出于何种原因,即使我将 head 变量引用到 newNode,我的程序也会打印 NULL,但它不会将字符串从 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;
}
【问题讨论】:
-
if (head == NULL) {head->s = newNode->s;指针不能这样工作。如果head没有指向任何东西,你就不能碰head->anything,它不存在。 -
所有其他链表帖子(有数千个)都有“仅修改本地头部”错误:(
-
由于您的代码不正确,不清楚您是将新节点插入到列表的开头还是列表的末尾。如果您将新节点插入到列表的开头,
printList将按照它们插入的相反顺序(LIFO 顺序)打印字符串。如果您将新节点插入到列表的末尾,printList将按照它们插入的顺序(FIFO 顺序)打印字符串。对于(单个)链表的 LIFO 排序,通常有一个变量指向链表的第一个(头)节点,另一个变量指向最后一个(尾)节点。
标签: c memory-management data-structures linked-list malloc