迭代的思想就是利用pre和cur两个指针,然后逐步向后遍历
# 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:
return
if not head.next:
return head
Newhead = self.reverseList(head.next)
head.next.next = head
head.next = None
return Newhead
'''
#迭代
if not head:
return
pre, cur = None, head
while cur:
cur.next, pre, cur = pre, cur, cur.next
'''
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
'''
return pre
'''