python3实现
- 循环方法:设置双指针,空间复杂度1,时间复杂度n
python
# 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: Optional[ListNode]) -> Optional[ListNode]:
cur, pre = head, None
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
这里返回的pre,因为结束循环的条件为cur为空,当cur为空时,pre正好为表头。
- 递归:注意递归设置的条件,第一次返回的表头
python
# 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: Optional[ListNode]) -> Optional[ListNode]:
def recur(cur, pre):
if not cur:
return pre
res = recur(cur.next, cur)
cur.next = pre
return res
return recur(head, None)