206.反转链表力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
题目描述
给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
示例
解题思路
反转一个链表有很多种方法,而本文我们将对下面两种方法进行代码实现。
1.更改原链表每一个节点的指向;
2.将原链表的节点按顺序头插到新的链表上。
1. 更改指向
当我们完成更改指向操作时,会达到以下效果。
代码
//直接更改指向
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* cur = head;//定义当前节点
struct ListNode* newhead = NULL;
while (cur)
{
struct ListNode* Next = cur->next;//保存当前节点的下一节点
cur->next = newhead;//将newhead赋给当前节点的下一节点
newhead = cur;//更新newhead位置
cur = Next;//更新cur的位置
}
return newhead;
}
接下来我来讲述上述操作具体是如何实现的 。
操作讲解
由于我们要更改单链表的指向,为了方便起见我们定义三个指针,cur,newhead,Next。
将cur,newhead,Next经过图中代码操作,将newhead赋给cur->next,更新newhead与cur,位置更换。直到cur为NULL时,newhead为5元素所在节点。此时newhead为链表的头节点,返回newhead。
2. 头插法
头插法会达成以下效果
代码
//头插法
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* cur = head;
struct ListNode* newhead = NULL;
while (cur)
{
struct ListNode* tmp = cur->next;
cur->next = newhead;
newhead = cur;
cur = tmp;
}
return newhead;
}
操作讲解
这一方法较之更改指向更为简单, 只需保存当前节点cur的下一节点,随后使用头插法将cur节点插入newhead中,最后返回newhead。
最终实现