From f8f8539393813c4f4ec73427d5eb157acc641fe1 Mon Sep 17 00:00:00 2001 From: Yifan Liu <39271063+yifanliuu@users.noreply.github.com> Date: Thu, 29 Jun 2023 13:49:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9Epython=E8=A7=A3=E6=B3=95?= =?UTF-8?q?=E9=80=92=E5=BD=92=E7=89=88=200024.=E4=B8=A4=E4=B8=A4=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E9=93=BE=E8=A1=A8=E4=B8=AD=E7=9A=84=E8=8A=82=E7=82=B9?= =?UTF-8?q?.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0024.两两交换链表中的节点.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) 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: