1、思路
模板题,记下来就好。
2、代码
//反转单链表
list_node * reverse_list(list_node * head)
{
if (head == nullptr || head->next == nullptr) return head;
list_node *pre = nullptr, *next = nullptr;
while (head != nullptr)
{
next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
//反转双链表
double_list_node * reverse_double_list(double_list_node * head)
{
if (head == nullptr || head->next == nullptr) return head;
double_list_node *pre = nullptr, *next = nullptr;
while (head != nullptr)
{
next = head->next;
head->next = pre;
head->pre = next; //与反转单链表不同的就是多了这一行
pre = head;
head = next;
}
return pre;
}