【发布时间】:2016-12-07 15:28:40
【问题描述】:
这部分代码有问题。我的目标是反转一个双向链表。当我尝试打印反向列表时收到垃圾值。
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);
}
我收到的输出:
原始列表:1 2 3 4 5 6 7
倒排列表:1 8532616 3 4 5 6 7 8528368 2002618240
【问题讨论】:
-
if(temp != NULL) lista->head = temp->prev;嗯?这是做什么的?列表有一个头指针和一个尾指针,它们应该怎么办? -
在您的
printList中,完成后调用free(ptr),这相当于free(NULL)什么都不做,但出于任何目的都不需要它。
标签: c data-structures struct reverse doubly-linked-list