【发布时间】:2021-06-01 02:48:28
【问题描述】:
我正在尝试在 C 中实现双向链表,但遇到了一些关于头部插入的问题。
LinkedListNode* CreateLinkedListNode(int data) {
LinkedListNode* node = (LinkedListNode*) malloc(sizeof(LinkedListNode*));
if (node == NULL) {
printf("Fail to create a linked list node");
exit(1);
}
node->prev = NULL;
node->next = NULL;
node->data = data;
return node;
}
void InsertLinkedList(LinkedListPtr list, int new_value) {
LinkedListNode* node = CreateLinkedListNode(new_value);
node->next = list->head;
if (list->head != NULL) {
printf("%d\n", node->data);
list->head->prev = node;
printf("%d\n", node->data);
}
if (isEmpty(list)) {
list->tail = node;
}
list->head = node;
list->num_elements++;
}
InsertLinkedList() 中的list->head->prev = node 执行后,节点的值被更改为某个随机数。
对这个问题有什么想法吗?
【问题讨论】:
标签: c data-structures doubly-linked-list