Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c075793

Browse files
🐱(link): 24. 两两交换链表中的节点
补充递归题解
1 parent 9e9cbb7 commit c075793

File tree

1 file changed

+51
-3
lines changed

1 file changed

+51
-3
lines changed

‎docs/data-structure/linked_list/README.md‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,14 +166,12 @@ class Solution(object):
166166

167167
## 24. 两两交换链表中的节点
168168

169-
### 思路
169+
### 解一:迭代
170170

171171
- 为方便统一化创建空节点 `cur`
172172
- 交换呗,没啥好说
173173
- 注意返回头节点
174174

175-
### Python
176-
177175
```python
178176
class Solution(object):
179177
def swapPairs(self, head):
@@ -195,6 +193,56 @@ class Solution(object):
195193
return first.next
196194
```
197195

196+
### 解二:递归
197+
198+
```python
199+
# Definition for singly-linked list.
200+
# class ListNode:
201+
# def __init__(self, x):
202+
# self.val = x
203+
# self.next = None
204+
205+
class Solution:
206+
def swapPairs(self, head: ListNode) -> ListNode:
207+
def helper(node, pre):
208+
if node is None or node.next is None:
209+
return
210+
next_node = node.next
211+
# 指针交换
212+
node.next = next_node.next
213+
next_node.next = node
214+
pre.next = next_node
215+
helper(node.next, node)
216+
217+
ans = ListNode(0)
218+
ans.next = head
219+
helper(head, ans)
220+
return ans.next
221+
```
222+
223+
优雅递归:
224+
225+
```python
226+
# Definition for singly-linked list.
227+
# class ListNode:
228+
# def __init__(self, x):
229+
# self.val = x
230+
# self.next = None
231+
232+
class Solution:
233+
def swapPairs(self, head: ListNode) -> ListNode:
234+
if head is None or head.next is None:
235+
return head
236+
237+
first_node = head
238+
second_node = head.next
239+
240+
first_node.next = self.swapPairs(second_node.next)
241+
second_node.next = first_node
242+
243+
return second_node
244+
```
245+
198246
## 25. K 个一组翻转链表
199247

200248
[原题链接](https://leetcode-cn.com/problems/reverse-nodes-in-k-group/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /