为什么在cpp中反转链表需要临时节点?
Why is temporary Node necessary in Reversing a linked list in cpp?
这是工作代码:
Node* Reverse(Node *head)
{
Node *prev = NULL;
Node *next;
Node *current = head;
while (current != NULL)
{
next = current -> next;
current -> next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
当我删除临时变量 current 时,这不起作用。
Node* Reverse(Node *head)
{
Node *prev = NULL;
// Node *current = head;
Node *next;
while (head != NULL)
{
next = head -> next;
head -> next = prev;
prev = head;
head = next;
}
return head;
}
我知道我们需要 next
因为我们必须在失去访问权限之前跟踪它。但是我想不出为什么临时变量 current
是必要的?任何帮助将不胜感激。
您不需要 current
变量。 (尽管它的名字 head
会令人困惑)
代码不同,因为您没有在第二个代码段中将 prev
分配给 head
。
Node* Reverse(Node *head)
{
Node *prev = NULL;
// Node *current = head;
Node *next;
while (head != NULL)
{
next = head -> next;
head -> next = prev;
prev = head;
head = next;
}
// or head=prev; return head;
return prev; // <---
}
这是工作代码:
Node* Reverse(Node *head)
{
Node *prev = NULL;
Node *next;
Node *current = head;
while (current != NULL)
{
next = current -> next;
current -> next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
当我删除临时变量 current 时,这不起作用。
Node* Reverse(Node *head)
{
Node *prev = NULL;
// Node *current = head;
Node *next;
while (head != NULL)
{
next = head -> next;
head -> next = prev;
prev = head;
head = next;
}
return head;
}
我知道我们需要 next
因为我们必须在失去访问权限之前跟踪它。但是我想不出为什么临时变量 current
是必要的?任何帮助将不胜感激。
您不需要 current
变量。 (尽管它的名字 head
会令人困惑)
代码不同,因为您没有在第二个代码段中将 prev
分配给 head
。
Node* Reverse(Node *head)
{
Node *prev = NULL;
// Node *current = head;
Node *next;
while (head != NULL)
{
next = head -> next;
head -> next = prev;
prev = head;
head = next;
}
// or head=prev; return head;
return prev; // <---
}