mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-04 19:28:07 +08:00
Update 递归反转链表的一部分.md
增加了python版本代码
This commit is contained in:
@ -218,4 +218,40 @@ ListNode reverseBetween(ListNode head, int m, int n) {
|
||||
<img src="../pictures/qrcode.jpg" width=200 >
|
||||
</p>
|
||||
|
||||
======其他语言代码======
|
||||
======其他语言代码======
|
||||
|
||||
[DiamondI](https://github.com/DiamondI) 提供python3版本代码:
|
||||
|
||||
思路:递归。时间复杂度为O(n),由于递归调用需要借助栈的空间,因此空间复杂度亦为O(n)。
|
||||
|
||||
```python3
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
class Solution:
|
||||
def __init__(self):
|
||||
self.__successor = None
|
||||
|
||||
def __reverseN(self, head: ListNode, n: int) -> ListNode:
|
||||
if n == 1:
|
||||
# 记录第 n + 1 个节点
|
||||
self.__successor = head.next;
|
||||
return head;
|
||||
# 以 head.next 为起点,需要反转前 n - 1 个节点
|
||||
last = self.__reverseN(head.next, n - 1);
|
||||
|
||||
head.next.next = head;
|
||||
# 让反转之后的 head 节点和后面的节点连起来
|
||||
head.next = self.__successor;
|
||||
return last;
|
||||
|
||||
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
|
||||
# base case
|
||||
if m == 1:
|
||||
return self.__reverseN(head, n);
|
||||
# 前进到反转的起点触发 base case
|
||||
head.next = self.reverseBetween(head.next, m - 1, n - 1);
|
||||
return head;
|
||||
```
|
||||
|
Reference in New Issue
Block a user