C 双向链表反转-打印出垃圾数据
我对这部分代码有问题。我的目标是扭转双重链接列表。当我试图打印出反向列表时,会收到垃圾值C 双向链表反转-打印出垃圾数据,c,data-structures,struct,reverse,doubly-linked-list,C,Data Structures,Struct,Reverse,Doubly Linked List,我对这部分代码有问题。我的目标是扭转双重链接列表。当我试图打印出反向列表时,会收到垃圾值 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 =
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);
}
我收到的输出:
原名单:1234567
撤销名单: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
}
为什么要释放printList()和reverse()中的节点? 在C中,您应该只释放先前分配的变量,例如malloc()。 在C函数中声明变量时,它将自动分配到堆栈或其他内存区域(甚至在CPU寄存器中)。它们也将在函数结束时自动释放。 如果您动态地分配节点,然后在“reverse”函数中释放它们,我希望在读取释放的节点时看到垃圾。 我试图删除“免费”调用,代码运行良好。
if(temp!=NULL)lista->head=temp->prev代码>嗯?这有什么用?列表有一个头指针和一个尾指针,它们会发生什么?在你的打印列表中,你调用free(ptr)
,这样做相当于free(NULL)
,它不做任何事情,但任何目的都不需要它。
#include <stdio.h>
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("");
}
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;
}
int main(void) {
List list = { NULL, NULL };
Node nodeArr[7];
int i;
for( i = 0; i < 7; i++ )
{
nodeArr[i].val = 7 - i;
nodeArr[i].prev = NULL;
nodeArr[i].next = NULL;
pushFront(&list, &nodeArr[i]);
}
printList(&list);
reverse(&list);
printList(&list);
// your code goes here
return 0;
}
1 2 3 4 5 6 7
7 6 5 4 3 2 1