-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseLinkedListII.py
More file actions
34 lines (29 loc) · 926 Bytes
/
reverseLinkedListII.py
File metadata and controls
34 lines (29 loc) · 926 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/reverse-linked-list-ii/
# Author: Miao Zhang
# Date: 2021-01-15
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
p = dummy
# p: the node before m
for i in range(m - 1):
p = p.next
pre = None
cur = p.next # reverse start node
# cur: from reverse start node to the node after the reverse end node
for i in range(n - m + 1):
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
p.next.next = cur
p.next = pre
return dummy.next