我正在嘗試使用以下程序來反轉鏈接列表。但最後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)。 –