2022年 11月 5日

Python 链表反转

# 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 head is None or head.next is None:
            return head 
        #3变量循环
        # p=head
        # q=head.next
        # head.next=None
        # while q:
        #     r=q.next
        #     q.next=p
        #     p=q
        #     q=r
        # head =p
        # return p
        
        # last=None
        # while head:
        #     tmp=head.next
        #     head.next=last
        #     last=head
        #     head=tmp
        # return last
        
        #递归
        else:#边界条件
            newhead=self.reverseList(head.next)
            head.next.next=head
            head.next=None
            return newhead
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

递归思路:

递归
注意:
1.当达到临界条件即head.next=None时,将head返回给newhead,并且newhead保持不变
2.head.next=None只在最后一句起作用,中间实际上没有什么作用,都被新的一轮递归覆盖了,在最后起作用保证尾节点指向None。

转载:
https://www.cnblogs.com/kubixuesheng/p/4394509.html
https://blog.csdn.net/Windows_Defender/article/details/80114246