206. 反转链表

# 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:
        self.head = None
        #不能用递归函数的返回值去return,因为递归函数的外部返回值是none
        self.exchange(head)
        return self.head

    def exchange(self, node):
        if node == None:
            return self.head
        tmp = self.head
        self.head = node
        #必须要新建一个临时节点,因为下面会操作node
        tmpnode = node.next
        self.head.next = tmp
        self.exchange(tmpnode)
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页