我正在尝试使用以下程序来反转链接列表。但最后head
仍错误地指向原始列表的第一个元素。我在哪里犯错?反转链接列表,为什么head不指向原始第一个元素?
#include <iostream>
struct node{
node(int val):
value(val),
next(nullptr)
{}
~node(){
delete next;
std::cout << "Deleting " << value << std::endl;
}
int value;
node* next;
};
node* create()
{
node * head = new node(1);
head->next = new node(2);
head->next->next = new node(3);
head->next->next->next = new node(4);
head->next->next->next->next = new node(5);
return head;
}
void print(node* head)
{
auto ptr = head;
while(ptr !=nullptr)
{
std::cout << ptr->value << " -> " ;
ptr = ptr->next;
}
std::cout << "nullptr" << std::endl;
}
void reverse(node** head_p)
{
auto head = *head_p;
auto p2 = head->next;
head->next = nullptr;
while(p2!=nullptr)
{
auto temp = head;
head = p2;
p2 = p2->next;
head->next = temp;
}
}
int main()
{
auto head = create();
print(head);
reverse(&head);
print(head);
delete head;
return 0;
}
什么是'删除下一个';'应该在'node'的析构函数中做? – Lingxi
@灵溪,它删除下一个节点。 – sank
[相关](http://codereview.stackexchange.com/q/45918/489)。 –