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 2652746

Browse files
🐱(link): 25. K 个一组翻转链表
1 parent ac503f1 commit 2652746

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

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

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,73 @@ class Solution(object):
199199
return first.next
200200
```
201201

202+
## 25. K 个一组翻转链表
203+
204+
[原题链接](https://leetcode-cn.com/problems/reverse-nodes-in-k-group/)
205+
206+
### 思路
207+
208+
模拟过程。
209+
210+
```python
211+
# Definition for singly-linked list.
212+
# class ListNode:
213+
# def __init__(self, x):
214+
# self.val = x
215+
# self.next = None
216+
217+
class Solution:
218+
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
219+
cur_idx = 0
220+
ans = ListNode(0)
221+
222+
# 计算链表长度
223+
length = 0
224+
tmp = head
225+
while tmp is not None:
226+
length += 1
227+
tmp = tmp.next
228+
229+
# 上一个节点
230+
pre = None
231+
pre_range_tail, range_head = ans, ans
232+
while head is not None and cur_idx + k <= length:
233+
for i in range(k):
234+
if i == 0:
235+
# 记录头部指针
236+
range_head = head
237+
if i == k - 1:
238+
# 记录尾部节点
239+
range_tail = head
240+
# 记录已遍历节点数量
241+
cur_idx += 1
242+
# 获取下一个节点
243+
next_node = head.next
244+
# 反转链表,指向上一个节点
245+
head.next = pre
246+
# 当前节点成为下一轮的「上一个节点」
247+
pre = head
248+
# 继续遍历下一个节点
249+
head = next_node
250+
# 前后两个链表相连
251+
pre_range_tail.next = range_tail
252+
# print(ans)
253+
pre_range_tail = range_head
254+
# print(ans)
255+
# 一轮结束,改变指针连接
256+
# range_head.next = head
257+
# 一轮结束后,改变 pre 指向
258+
pre = None
259+
260+
# 如果有剩余节点,继续连接
261+
range_head.next = head
262+
263+
return ans.next
264+
```
265+
266+
- 事件复杂度:O(n)
267+
- 空间复杂度:O(1)
268+
202269
## 61. 旋转链表
203270

204271
[原题链接](https://leetcode-cn.com/problems/rotate-list/solution/chuan-zhen-yin-xian-by-liweiwei1419/)

0 commit comments

Comments
(0)

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