-
题目链接 https://leetcode-cn.com/problems/reverse-linked-list-ii/
-
题目描述
- 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
-
输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL
-
解题思路
- 维护一个index变量来记录下一个节点是否是第m个节点
- 如果是第m个节点,那么对下一个节点采用头插法重建链表,直到第n个节点
- 剩余节点连接到第m个节点后面
-
代码
- python
class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: if not head or not head.next: return head # 记录 res, i = ListNode(0), 0 res.next = head tmp = res while head and i < m - 1: tmp, head, i = tmp.next, head.next, i + 1 #showList(head) # 反转 last = head while head and i < n: tmp1, head = head, head.next tmp.next, tmp1.next = tmp1, tmp.next i += 1 #showList(tmp) #showList(res) # 连接 if last: last.next = head return res.next
- python