Merge pull request #2155 from yifanliuu/patch-1

新增python解法递归版 0024.两两交换链表中的节点.md
This commit is contained in:
程序员Carl
2023-07-17 09:43:46 +08:00
committed by GitHub

View File

@ -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: