跳到主要内容

92. 反转链表 II(Medium)

题目描述

Leetcode 地址

反转从位置 mn 的链表。请使用一趟扫描完成反转。

样例

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Ouput: 1->4->3->2->5->NULL

解题思路

代码

class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
pre, cur = None, head
for _ in range(m - 1):
pre = cur
cur = cur.next
before, after = pre, cur

for _ in range(n - m + 1):
cur_next_bak = cur.next
cur.next = pre

pre = cur
cur = cur_next_bak
if before:
before.next = pre
else:
head = pre
after.next = cur
return head