leetcode 206.反转链表
大家好,我是小学五年级在读的蒟蒻,专注于后端,一起见证蒟蒻的成长,您的评论与赞与关注是我的最大动力,如有错误还请不吝赐教,万分感谢。一起支持原创吧!纯手打有笔误还望谅解。
题目描述
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
题解一
使用双指针和头插法求解
思路:开辟一个新空间来使用头插法将原链表的数据不断插入新开辟的链表中
/*
* @lc app=leetcode.cn id=206 lang=cpp
*
* [206] 反转链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *reverseList(ListNode *head)
{
ListNode *reHead = NULL;
ListNode *cur = head;
ListNode *tmp;
while (cur)
{
tmp = cur->next;
cur->next = reHead;
reHead = cur;
cur = tmp;
}
return reHead;
}
};
// @lc code=end
题解二
使用递归反转链表
思路:主要还是遍历节点,在遍历每个节点的时候就开始反转链表,这样递归下去,到最后的时候就可以完成链表的反转了
/*
* @lc app=leetcode.cn id=206 lang=cpp
*
* [206] 反转链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *reverse(ListNode *cur, ListNode *pre)
{
//遍历结束
if (pre == nullptr)
{
return cur;
}
//每一步都反转链表
ListNode *tmp = pre->next;
pre->next = cur;
cur = pre;
pre = tmp;
//进入递归
return reverse(cur, pre);
}
ListNode *reverseList(ListNode *head)
{
//将反转后的链表尾部null值传入
ListNode *cur = nullptr;
ListNode *pre = head;
return reverse(cur, pre);
}
};
// @lc code=end