mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2155 from yifanliuu/patch-1
新增python解法递归版 0024.两两交换链表中的节点.md
This commit is contained in:
@ -177,6 +177,30 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
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
|
```python
|
||||||
# Definition for singly-linked list.
|
# Definition for singly-linked list.
|
||||||
# class ListNode:
|
# class ListNode:
|
||||||
|
Reference in New Issue
Block a user