逆序一个链表常用方法有以下几种:
- 就地逆置
- 头插法
先初始化一个链表
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL){}
};
ListNode a(10);
ListNode b(20);
ListNode c(30);
ListNode d(40);
ListNode e(50);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
ListNode *head = &a;
使用循环逆置链表(常规)【也叫 就地逆置法】
int main()
{
// 打印旧的节点
while(head)
{
cout << head->val << " " << head->next << endl ;
head = head->next;
}
head = &a; // 重置到头结点
// 开始逆序
ListNode *next = nullptr;
ListNode *new_head = nullptr;
// for(int i = 0; i < 5; ++i) // 需要知道有几个节点
while(head)
{
next = head->next; // 备份head 得 next的节点
head->next = new_head; // 断开当前节点,并 和 已经逆序的链接, 形成新的 链表
new_head = head; // 更新 新的链表
head = next; // head 获取剩余 节点
}
head = new_head;
// 打印逆序后的节点
while(head)
{
cout << head->val << " " << head->next << endl ;
head = head->next;
}
return 0;
}
头插法
// 打印旧的节点
while(head)
{
cout << head->val << " " << head->next << endl ;
head = head->next;
}
head = &a;
// 开始逆序
ListNode *next = nullptr;
ListNode tmp_head(0);
while(head)
{
next = head->next;
head->next = tmp_head.next;
tmp_head.next = head;
head = next;
}
head = tmp_head.next;
while(head)
{
cout << head->val << " " << head->next << endl ;
head = head->next;
}
两种方法的比较: