c - 为什么我用这个方法反向的时候原来的双链被修改了?

标签 c pointers doubly-linked-list

我正在尝试使用迭代方法反转双向链表,我对原始列表被修改的部分感到震惊,即使我没有使用指向原始列表的指针样式修改。

这是我正在使用的反向函数,head 是在 main 中声明的局部变量 像 Node* head = NULL; 并且已经填充了一组值。

Node* reverse_iterative(Node* head)
{
    if(head == NULL || head->next == NULL)
        return head;

    Node *prev, *current=head, *temp;
    while(current != NULL)
    {
        current->prev = current->next;
        current->next = temp;
        temp = current;
        current = current->prev;
    }
    return temp;
}

这就是我在 main 中使用它的方式:

Node* rev = NULL;
rev = reverse_iterative(head);

这是我得到的输出:

original list: 15 <=>25 <=>35 <=>45 <=>55 <=>65 <=>75 <=>
making the list actually reverse: 75 <=>65 <=>55 <=>45 <=>35 <=>25 <=>15 <=>
after reversing, the original list now: 15 <=>

我无法获取原始头节点被修改的部分。

最佳答案

仔细查看您的 while 循环,并考虑以下语句在循环的初始迭代:

current->next = temp;

在赋值时 temp 中有什么?公开更多代码,我们有:

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

请注意,temp 是未初始化的,因此是一个未定义的指针值。您原来的 head-ptr next ptr 正在重置为未初始化临时文件中保存的垃圾。

通过执行以下操作解决此问题:

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

我还没有机会对其进行测试,但这应该会让您更接近您正在寻找的东西。

关于c - 为什么我用这个方法反向的时候原来的双链被修改了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13128098/

相关文章:

您可以使用指向包含结构的指针来修改嵌套结构的值吗?

c - 提供的代码中的 "Dereferencing Pointer to Incomplete Type"

c - 为什么这个程序会这样呢? C

c++ - 信息实际上并未存储在节点数组中

c - 唐叶算法 : splitting strings

c - 请解释输出

c - 内存分配C

c - 我可以改变指针的功能吗?

java - 计算有多少个 "element"出现在双向链表中

c++ - 双链表实现