diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index ab204d89..d7c03b64 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -177,6 +177,30 @@ class Solution { ``` Python: +```python +# 递归版本 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head is None or head.next is None: + return head + + # 待翻转的两个node分别是pre和cur + pre = head + cur = head.next + next = head.next.next + + cur.next = pre # 交换 + pre.next = self.swapPairs(next) # 将以next为head的后续链表两两交换 + + return cur +``` + ```python # Definition for singly-linked list. # class ListNode: