一、题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-linked-list
二、提供方便走读代码的图
三、题目代码
思路一:迭代法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL)
return head;
struct ListNode* p=NULL;
struct ListNode* p1=head;
struct ListNode* p2=head->next;
while(p1)
{
p1->next=p;
p=p1;
p1=p2;
if(p2)
p2=p2->next;
}
return p;
}
思路二:头插法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* newhead=NULL;
struct ListNode* cur=head;
while(cur)
{
//保存下一个
struct ListNode* next=cur->next;
//头插
cur->next=newhead;
newhead=cur;
//迭代往后
cur=next;
}
return newhead;
}
思路三:递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL||head->next==NULL)
return head;
struct ListNode* pre=head->next;
struct ListNode* p=reverseList(pre);
pre->next=head;
head->next=NULL;
return p;
}
以上是本篇文章的全部内容,如果文章有错误或者有看不懂的地方,多和喵博主交流。互相学习互相进步。如果这篇文章对你有帮助,可以给喵博主一个关注,你们的支持是我最大的动力。