题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
- 没注解
class Solution:
def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode:
# write code here
pre=None
cur=head
if m==n:
return head
for i in range(m-1):
pre = cur
cur = cur.next
m_pre = pre
m_cur = cur
for i in range(n-m+1):
tnext = cur.next
cur.next= pre
pre=cur
cur=tnext
if m_pre:
m_pre.next = pre
else:
head = pre
m_cur.next = cur
return head
- 有注解
class Solution:
def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode:
# write code here
pre=None
cur=head
# 1->2->3->4->5
# p c
# 当m==n时,不需要反转
if m==n:
return head
# 让cur移到m位置下
for i in range(m-1):
pre = cur
cur = cur.next
m_pre = pre
m_cur = cur
# 此时情况
# 1->2->3->4->5
# p c
# mp mc (为了表示方便,这里的mp时变量m_pre, mc是变量m_cur)
# 反转开始
for i in range(n-m+1):
tnext = cur.next
cur.next= pre
pre=cur
cur=tnext
# 反转结束, 此时情况
# 1<-2<-3<-4 5
# mp mc p c
# 微调
if m_pre:
m_pre.next = pre
else:
#当m=1时, m_pre是None, 没有.next属性,
head = pre
m_cur.next = cur
# 调整结束此时情况
# 1->4 5<-2<-3<-4 即1 4 3 2 5
return head