gpt4 book ai didi

c - 双向链表逆向——打印出垃圾数据

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

这部分代码有问题。我的目标是反转双向链表。当我尝试打印出反向列表时,我收到垃圾值。

typedef struct node{
int val;
struct node* prev;
struct node* next;
}Node;

typedef struct list{
Node* head;
Node* tail;
}List;

void pushFront(List* l, Node* node){
if(l->head == NULL){
l->head = node;
l->tail = node;
l->tail->next = NULL;
}else{
l->head->prev = node;
node->next = l->head;
l->head = node;
}
}
void printList(List* list){

Node *ptr = list->head;
while(ptr != NULL){
printf("%i ",ptr->val);
ptr = ptr->next;
}
puts("");
free(ptr);
}

void reverse(List* lista){

Node* ptr = lista->head;
Node* temp = NULL;
while(ptr != NULL){
temp = ptr->prev;
ptr->prev = ptr->next;
ptr->next = temp;
ptr = ptr->prev;
}

if(temp != NULL)
lista->head = temp->prev;
free(ptr);
free(temp);
}

我收到的输出:

Original list: 1 2 3 4 5 6 7

Reversed list: 1 8532616 3 4 5 6 7 8528368 2002618240

最佳答案

我猜你使用了你的函数 printList在同一个列表上两次(一次在反转列表之前和一次之后),这会导致在 printList 期间释放列表时出现未定义的行为。然后尝试访问和使用这些相同的内存位置 -> 未完成时不要释放你的东西:

void printList(List* list){

Node *ptr = list->head;
while(ptr != NULL){
printf("%i ",ptr->val);
ptr = ptr->next;
}
puts("");
// free(ptr); --> Remove this line
}

关于c - 双向链表逆向——打印出垃圾数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38717669/

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