为什么这两个不同的反向双链表?

问题描述

反转双向链表,这两个代码有什么区别? 不是和改变next和prevIoUs指针一样吗?

void reverse(Node **head_ref) 
{ 
    Node *temp = NULL; 
    Node *current = *head_ref; 

    while (current != NULL) 
    { 
        temp = current->prev; 
        current->prev = current->next; 
        current->next = temp;             
        current = current->prev; 
    } 

    if(temp != NULL ) 
        *head_ref = temp->prev; 
} 

void reverse(Node **head_ref) 
{ 
    Node *temp = NULL; 
    Node *current = *head_ref; 

    while (current != NULL) 
    { 
        temp = current->next;
        current->next; = current->prev; 
        current->prev = temp;             
        current = current->next; 
    } 

    if(temp != NULL ) 
        *head_ref = temp->next;
} 

解决方法

当您交换两个引用时,您确实可以选择从哪一个开始,即将哪一个复制到 temp 变量中。

于是下面两段代码就成功实现了交换:

    temp = current->prev; 
    current->prev = current->next; 
    current->next = temp;             

而且(如果你去掉了一半的分号):

    temp = current->next; 
    current->next = current->prev; 
    current->prev = temp;             

但是,您的第二个代码块应该像第一个代码块一样继续。您必须点击 prev 链接(在交换之前,它是 next 链接)。所以在第二个版本中你应该改变:

    current = current->next; 

到:

    current = current->prev; 

仍然,第二个代码中的问题是,在每次迭代结束时,您的 temp 引用等于 current 引用,并且在循环退出时将为 null。这样就无法在循环退出后正确设置头指针。

所以你应该坚持使用第一个版本。