方法一:多指针
# 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:
pre=None
cur=head
while cur:
temp=cur.next
cur.next=pre
pre=cur
cur=temp
return pre
方法二:递归
# 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 not head.next:
return head
else:
cur=self.reverseList(head.next)
head.next.next=head
head.next=None
return cur
总结
- 双指针法相对来说好理解,递归法head.next.next=head这句话不好理解
- 返回链表时只需要返回head就是返回整个链表
本文介绍两种链表反转的方法:双指针法和递归法。双指针法通过迭代实现链表节点指向的反转,而递归法则利用递归特性反转链表。递归法中head.next.next=head这一句较为复杂,需要深入理解。
228

被折叠的 条评论
为什么被折叠?



