本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
206.反转链表
来源:力扣(LeetCode)
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:

输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
解法
- 暴力法:链表题目转成数组题目就好做了,这种方法会造成空间的增多,最后变成反转数组,再将数组变成链表即可;
- 循环:for循环,原地进行前后反转,注意保存截断后的元素,进一步开始遍历;
- 递归:每次拿出一个元素,剩余部分是类似的子问题,然后再将其进行拼接即可;
代码实现
暴力法
这里不做实现,一般不会让这样做; 复杂度分析
- 时间复杂度: 排序虽然也花时间,但可以忽略不计
- 空间复杂度:
循环
python实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
prev = None
while head:
tmp = head.next # 保存截断的元素
head.next = prev # 进行截断
prev = head # 往后挪动
head = tmp
return prev
c++实现
/**
* 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) {
if (head == nullptr || head->next == nullptr){
return head;
}
ListNode *prev = nullptr;
while (head){
ListNode *pNext = head->next;
head->next = prev;
prev = head;
head = pNext;
}
return prev; // 这里是prev, 因为最后head是None
}
};
复杂度分析
- 时间复杂度: 遍历一遍
- 空间复杂度:
递归
python实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur = self.reverseList(head.next) # 下一个元素 子问题
head.next.next = head # head.next变成反转链表后的最后一个,将head接上去
head.next = None
return cur
c++实现
/**
* 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) {
if (head == nullptr || head->next == nullptr){
return head;
}
ListNode *cur = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return cur;
}
};
复杂度分析
- 时间复杂度:
- 空间复杂度: 空间复杂度取决于递归栈调用的栈空间,最多为n层