地址:https://leetcode-cn.com/problems/reverse-linked-list/
1、循环法
# 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:
curr,prev = head,None
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
2、递归法
# 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.next is None or head is None:
retun head.next
p = self.reverseList(head.next)
head.next.next = head
head.next = None
retun p