Skip to content

Commit 1828803

Browse files
k个一组反转链表 (labuladong#350)
Co-authored-by: Kristifler <[email protected]>
1 parent c14be72 commit 1828803

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

高频面试系列/k个一组反转链表.md

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,51 @@ private:
175175
![labuladong](../pictures/labuladong.jpg)
176176
177177
178+
179+
[KAGAWA317](https://github.com/KAGAWA317) 提供Python3解法代码:
180+
181+
```python
182+
# 反转区间 [a, b) 的元素
183+
def reverse(a, b):
184+
pre = None
185+
cur = a
186+
while cur != b:
187+
cur.next, pre, cur = pre, cur, cur.next
188+
return pre
189+
```
190+
191+
[KAGAWA317](https://github.com/KAGAWA317) 提供Python3解法代码:
192+
193+
```python
194+
class Solution:
195+
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
196+
if not head:
197+
return
198+
# 区间 [a, b) 包含 k 个待反转元素
199+
a = b = head
200+
for _ in range(k):
201+
# 不足 k 个,不需要反转,base case
202+
if not b:
203+
return head
204+
b = b.next
205+
206+
# 反转区间 [a, b) 的元素
207+
def reverse(a, b):
208+
pre = None
209+
cur = a
210+
while cur != b:
211+
cur.next, pre, cur = pre, cur, cur.next
212+
return pre
213+
214+
# 反转前 k 个元素
215+
newHead = reverse(a, b)
216+
# 递归反转后续链表并连接起来
217+
a.next = self.reverseKGroup(b, k)
218+
return newHead
219+
```
220+
178221
[上一篇:如何寻找最长回文子串](../高频面试系列/最长回文子串.md)
179222
180223
[下一篇:如何判定括号合法性](../高频面试系列/合法括号判定.md)
181224
182-
[目录](../README.md#目录)
225+
[目录](../README.md#目录)

0 commit comments

Comments
 (0)