递归反转链表的一部分思路
一、递归反转整个链表
剑指 Offer 24. 反转链表 -重点
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# 递归终止条件是当前为空,或者下一个节点为空
if(head==None or head.next==None):
return head
# 这里的cur就是最后一个节点
cur = self.reverseList(head.next)
# 这里请配合动画演示理解
# 如果链表是 1->2->3->4->5,那么此时的cur就是5
# 而head是4,head的下一个是5,下下一个是空
# 所以head.next.next 就是5->4
head.next.next = head
# 防止链表循环,需要将head.next设置为空
head.next = None
# 每层递归函数都返回cur,也就是最后一个节点
return cur
# 双指针迭代
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head==None or head.next==None:
return head
pre=None
cur=head
while cur:
tmp=cur.next
cur.next=pre
pre=cur
cur=tmp
return pre
二、反转链表前 N 个节点
三、反转链表的一部分
四、最后总结
92. 反转链表 II
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
def reverseN(head,n):
if n == 1:
return head
# 以 head.next 为起点,需要反转前 n - 1 个节点
last = reverseN(head.next, n-1)
successor = head.next.next
# 以head.next为开头的链表已经完成翻转,那么head.next.next正确指向后继节点
head.next.next = head
head.next = successor
return last
if m == 1:return reverseN(head,n)
head.next = self.reverseBetween(head.next,m-1,n-1)
return head
剑指 Offer 06. 从尾到头打印链表-简单
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
if not head :
return []
res=[]
while head:
res.append(head.val)
head=head.next
return res[::-1]
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
return self.reversePrint(head.next)+[head.val] if head else[]