C++ 为什么我的双链接列表的反转失败了?
我试图使用如下所示的reverseList()函数反转一个双链接列表,但我没有得到我所期望的结果,我没有发现我的逻辑中有任何错误,但请提供帮助C++ 为什么我的双链接列表的反转失败了?,c++,data-structures,reverse,doubly-linked-list,C++,Data Structures,Reverse,Doubly Linked List,我试图使用如下所示的reverseList()函数反转一个双链接列表,但我没有得到我所期望的结果,我没有发现我的逻辑中有任何错误,但请提供帮助 void reverseList(Node **head) { Node *i,*temp=*head; while(temp!=NULL) { i=temp->next; temp->next=temp->prev; temp->prev=i;
void reverseList(Node **head)
{
Node *i,*temp=*head;
while(temp!=NULL)
{
i=temp->next;
temp->next=temp->prev;
temp->prev=i;
/*This if block is to ensure that the head may never get a null value,
as temp is assigned to head after the loop,
ie, temp=i; doesn't execute only for the last iteration*/
if(i!=NULL)
temp=i;
}
*head=temp;
}
您的代码不起作用,因为您没有向前或向后移动指针。另外,您不需要返回头指针,因为您已经在传递指针的指针。
如果已明确告知您反转上一个和下一个指针,则可以使用上述代码。否则,不管您需要什么,都可以从头或尾遍历列表。使用调试器…这将永远循环,原因之一是
temp=NULL
始终为真,因为如果(i!=NULL)temp=i代码>永远不会将temp设置为NULL。(除非列表为空,在这种情况下,temp开始时为NULL)好的,要摆脱无限循环,我将循环条件更改为,while(temp->next!=NULL),但现在至少我的反向列表只有原始列表的最后一个节点作为其头。虽然没有回答,我建议保持swap
部件清洁,独立于I
。(可能使用std::swap
)“我没有得到我所期望的”——这是相当缺乏信息的。有一个结果是你所期望的,也有无数个结果是你所不期望的。解释你的症状不仅有助于人们回答问题,而且也有助于下一个有同样问题的人(如果有人发现这个问题)。仅供参考,这可以大大简化。
void reverse(Node **head)
{
Node *temp = NULL;
Node *current = *head;
while (current != NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
/* Before changing head, check for the cases like empty
list and list with only one node */
if(temp != NULL )
*head = temp->prev;
}