新增python解法递归版 0024.两两交换链表中的节点.md

This commit is contained in:
Yifan Liu
2023-06-29 13:49:22 +08:00
committed by GitHub
parent 496f80d879
commit f8f8539393

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: