我正在尝试使用迭代方法反转双向链表,我对原始列表被修改的部分感到震惊,即使我没有使用指向原始列表的指针样式修改。
这是我正在使用的反向函数,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/