gpt4 book ai didi

C:双向链表中的段错误,在追加和删除函数中

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:51 26 4
gpt4 key购买 nike

我在用 C 语言创建双向链表时遇到问题,因为它在追加和删除时返回段错误。好像我将其中一个指针指向了错误的位置,但我很难找到它。

我的问题函数如下:

追加:

int list_append(list_t *list, int val) {
if(!list) { return 1; }

// create a new node, then assign the value
struct node_t *new = (node_t *) malloc(sizeof(node_t));
new->val = val;
new->prev = NULL;
new->next = NULL;

// place the new node (since it is tail, make next null)
new->next = NULL;

// if there's no head(null), make the new node the head (and tail)
if (list->head == NULL)
{
list->head = new;
}

// if the next value is not null, traverse until it is (=tail)
struct node_t *node = list->head;

while (node)
{
node = list->tail;
}
// place the new node at the next of tail
list->tail->next = new;

// set the old tail as the previous of new node
new->prev = list->tail;

list->tail->next = NULL;

CHECK_LIST(list);

return 0;
}

删除:

int list_delete(list_t *list, int val) {
if(!list) { return 1; }

CHECK_LIST(list);

// make a temporary node to help find the value
struct node_t *temp = list->head;


// start traversing the list

while (temp)
{

// if match is found
if (temp->val == val)
{
// if the match is actually the head, make the next node the new head,
// then make old head null
if (temp == list->head)
{
list->head = list->head->next;
list->head->prev = NULL;
}
// if the match is at the tail, make the previous node the new tail,
// then make the old tail null
if (temp == list->tail)
{
list->tail = list->tail->prev;
temp->prev->next = NULL;
} else
{
// set new next of temp as the old next of temp, and vice versa
// then, free temp from memory
temp->next = temp->prev->next;
temp->prev = temp->next->prev;

temp = NULL;
free(temp);
}
}

// keep moving
temp = temp->next;
}

CHECK_LIST(list);

return 0;
}

提前感谢您的帮助。

最佳答案

append() 函数的以下代码块中存在错误

while (node) {
node = list->tail; /*what is tail here ?? */
}
/* after this loop you are not using node anywhere, what's the use
of iterating through loop */
// place the new node at the next of tail
list->tail->next = new;
// set the old tail as the previous of new node
new->prev = list->tail;
list->tail->next = NULL;

替换为

struct node_t *node = list->head;

while (node->next) {/* when loop fails node holds last node address */
node = list->next;
}
node->next = new; /* replace node->next as new node */
new->prev = node->next; /* new node previous make it as old node next */
new->next = NULL;/* last node next make it as 0*/

最好先运行 gdb 然后执行 bt

关于C:双向链表中的段错误,在追加和删除函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com