一、刷题内容
原题链接
https://leetcode-cn.com/problems/reverse-linked-list/
内容描述
给你单链表的头节点 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
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
二、解题方法
1.方法一:迭代
(1)、迭代需要三个指针,pre,cur,nxt,分别按顺序指向三个节点
(2)、三个指针的初始化:pre指向空节点,cur指向头结点head,nxt指向head.next
因为head.next可能不存在,nxt在循环中定义,这样如果head为空就不会进入循环
(3)、迭代过程
nxt指向cur.next
cur.next指向pre
pre移动到cur位置
cur移动到nxt位置
(4)、当cur为空时,返回pre
# 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:
pre, cur = None, head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
时间复杂度:O(n)
空间复杂度:O(1)
2.方法二:递归
(1)、递归上来就先写终止条件:如果head为空或者head.next为空,返回head
(2)、新头结点newHead指向尾结点,此处进入递归,递归一直到遍历到尾结点时才会返回
(3)、每一层递归,该层递归中的head会让下一个节点指向自己,head.next.next = head;然后head自己指向空。以此达到反转的目的。
(4)、返回新链表的头结点newHead
# 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 not head or not head.next:
return head
newhead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newhead
时间复杂度:O(n)
空间复杂度:O(n)
3.方法三:列表和reverse函数
# 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:
res = []
while head:
res.append(head.val)
head = head.next
ans = ListNode()
t = ans
res.reverse()
for n in res:
t.next = ListNode()
t = t.next
t.val = n
return ans.next