C语言 在我的双链表中添加新的第一个节点时,我的辅助节点数据被替换为垃圾



我正在为学校做一个实验室,我们应该实现函数来练习使用链表。我不能通过断言(getFirstElement(head) == 2),因为数据只是垃圾(16040,32030,你明白的想法)。

当我调试时,似乎数据确实被正确启动,只是在我将节点链接到列表时随机被替换。

下面是我写的分配和初始化函数(给出了函数头和名称)。一切正常,并且它确实在第二个节点中保存了正确的数据,直到这里->

struct node
{
Data data;
struct node *next;
struct node *previous;
};
typedef struct node *List;
typedef int Data;
List createEmptyList(void)
{
return NULL;
}
static struct node* createListNode(const Data data)
{
struct node* newNode = (struct node*)calloc(1, sizeof(struct node*));

if (newNode == NULL)
{
printf("Error");
return NULL;
}
else
{
newNode->data = data;
newNode->next = NULL;
newNode->previous = NULL;
return newNode;
}
}

void addFirst(List *list, const Data data)
{
List newNode = createListNode(data);
newNode->next = (*list);
if (*list != NULL)
{
(*list)->previous = newNode;   <- After this line the second nodes data turns into garbage
}
(*list) = newNode;

assert(*list != NULL);
}
void testFunction(List head)
{
printf("Starting testn");

assert(isEmpty(head));
addFirst(&head, 6);
addFirst(&head, 5);
addFirst(&head, 4);
addFirst(&head, 3);
addFirst(&head, 2);
assert(numberOfNodesInList(head) == 5);
assert(getFirstElement(head) == 2);
}
int main(void)
{
List head = createEmptyList();

testFunction(head);

return 0;
}

我已经添加了我卡住的部分代码。

我不明白哪里出错了,任何帮助都是感激的!其他一切似乎都很好。

Data只是一个int型,它是由老师定义的

函数createListNode

static struct node* createListNode(const Data data)
{
struct node* newNode = (struct node*)calloc(1, sizeof(struct node*));
//...

您正在为指针分配内存,而不是为类型为struct node的对象分配内存。

你需要写

struct node* newNode = (struct node*)calloc(1, sizeof(struct node));

struct node* newNode = (struct node*)calloc(1, sizeof( *newNode ));

注意这个typedef声明

typedef int Data;

必须在结构体struct node

声明之前同样在函数addFirst

void addFirst(List *list, const Data data)
{
List newNode = createListNode(data);
//...

需要检查newNode是否为空指针。

最新更新