任务描述
思路
- 递归思想,先反转head之后的节点,再将head连到返回的反转链表末尾
- 迭代,三指针迭代
遇到问题
- 原因:当head.next = None时,下一次递归传入的参数为None,该参数没有next属性
- 修改:循环前判断传入参数是否为空
- 迭代时没有考虑l3.next = None的情况
- 只输出了最后两个节点,原因在于循环中l1.next = None,每次循环时,l1所指向的节点都无法和下一个节点有链接,造成最后一个循环时,链表只含两个节点
while l2:
l3 = l2.next
l2.next = l1
l1.next = None
l1 = l2
l2 = l3
return l1
代码实现
- 递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or head.next == None:
return head
res = self.reverseList(head.next) # res指向反转后链表的头部
head.next.next = head
head.next = None
return res
- 迭代:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or head.next == None:
return head
l1 = head
l2 = head.next
l3 = l2
l1.next = None
while l2:
l3 = l2.next
l2.next = l1
l1 = l2
l2 = l3
return l1