方法一:多指针
# 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就是返回整个链表