遍历解法
当指针混乱时,设置新的遍历储存指针
# 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:
pre = ListNode()
pre.next = head
cur = pre
while head and head.next:
head_next = head.next
cur_next = cur.next
cur.next = head.next
head.next = head.next.next
head_next.next = cur_next
return pre.next
递归解法
动手画框框 递归的思想 想好停止条件 开始画过程
# 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 not head or not head.next:
return head
cur = self.reverseList(head.next)
head.next.next = head
head.next = None
return cur