-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.py
37 lines (31 loc) · 872 Bytes
/
solution.py
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
35
36
37
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if m == n: return head
dummy = ListNode(-1)
dummy.next = head
pre = dummy
for i in xrange(m - 1):
pre = pre.next
# reverse the [m, n] nodes
reverse = None
cur = pre.next
for i in xrange(n - m + 1):
nxt = cur.next
cur.next = reverse
reverse = cur
cur = nxt
# the tail of reverse
pre.next.next = cur
pre.next = reverse
return dummy.next