File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed
docs/data-structure/linked_list Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change @@ -286,6 +286,80 @@ class Solution(object):
286286 return head
287287```
288288
289+ ## 92. 反转链表 II
290+
291+ [ 原题链接] ( https://leetcode-cn.com/problems/reverse-linked-list-ii/ )
292+
293+ ### 思路
294+
295+ 需要找到几个关键节点:
296+
297+ 1 . 开始翻转的节点 ` begin `
298+ 2 . 开始翻转节点的前一个节点 ` begin_pre `
299+ 3 . 结束翻转的节点 ` end `
300+ 4 . 结束翻转节点的下一个节点 ` end_next `
301+
302+ 从 ` begin ` 到 ` end ` 位置执行反转操作。此段链表翻转后需要:
303+
304+ 1 . 修改 ` begin_pre ` 节点的指针,指向 ` end ` 节点:` begin_pre.next = end `
305+ 2 . 修改 ` begin ` 节点的指针,指向 ` end_next ` 节点:` begin.next = end_next `
306+
307+ 注意:` m ` 可能会等于 ` n ` 。
308+
309+ ``` python
310+ # Definition for singly-linked list.
311+ # class ListNode:
312+ # def __init__(self, x):
313+ # self.val = x
314+ # self.next = None
315+
316+ class Solution :
317+ def reverseBetween (self , head : ListNode, m : int , n : int ) -> ListNode:
318+ if head is None :
319+ return head
320+
321+ if m == n:
322+ return head
323+
324+ index = 0
325+ pre = None
326+ cur = head
327+ begin_pre = None
328+ begin = None
329+ end = None
330+ end_next = None
331+
332+ while cur is not None :
333+ index += 1
334+ next_cur = cur.next
335+
336+ if index == m:
337+ # 记录开始节点
338+ begin = cur
339+ if index == m - 1 :
340+ begin_pre = cur
341+ if index == n:
342+ # 记录结束位置
343+ end = cur
344+ if index == n + 1 :
345+ end_next = cur
346+
347+ if index > m and index <= n:
348+ # 翻转
349+ cur.next = pre
350+ pre = cur
351+ cur = next_cur
352+
353+ # 修改指针位置
354+ begin.next = end_next
355+ if begin_pre is None :
356+ # 从头开始翻转了
357+ return end
358+ else :
359+ begin_pre.next = end
360+ return head
361+ ```
362+
289363
290364## 138. 复制带随机指针的链表
291365
You can’t perform that action at this time.
0 commit comments