标签:next span none 调整 += 复杂 col art rev
题目:给定一个单向链表的头节点head,以及两个整数from和to,在单向链表上把第from个节点到第to个节点这一部分进行反转
例如:
1 --> 2 --> 3 --> 4 --> 5 --> null, from=2, to=4
调整结果为: 1 --> 4 --> 3 --> 2 --> 5 --> null
再如:
1 --> 2 --> 3 --> null, from=1, to=3
调整结果为:3 --> 2 --> 1 --> null
要求:
1. 如果链表长度为N,时间复杂度要求为O(N),额外空间复杂度要求为O(1)
2. 如果不满足,1<=from<=to<=N,则不用调整
My:
1 def reversePart(L, _from, to): 2 if _from < 1 or _from > to or to > L.length: 3 return 4 p = L.head 5 # 找到待反转链表的开始部分 6 count = 1 7 while count < _from: 8 p = p.next_item 9 count += 1 10 q = p 11 # 反转部分单向链表 12 pre = p 13 p = p.next_item 14 next = None 15 while count <= to: 16 next = p.next_item 17 p.next_item = pre 18 pre = p 19 p = next 20 count += 1 21 # 将原链表与反转的部分链表连接起来 22 q.next_item.next_item = p 23 q.next_item = pre
Reference:
1 def reversePart(L, _from, to): 2 count = 0 3 fpre = None 4 tpos = None 5 p = L.head 6 # 找到待反转链表的前驱节点和后继节点 7 while(p != None): 8 fpre = p if count==_from-1 else fpre 9 tpos = p if count==to+1 else tpos 10 count += 1 11 p = p.next 12 if _from > to or _from < 1 or to > L.length: 13 return 14 pre = L.head if fpre==None else fpre.next 15 p = pre.next 16 pre.next = tpos 17 next = None 18 while p != tpos: 19 next = p.next 20 p.next = pre 21 pre = p 22 p = next 23 if fpre != None: 24 fpre.next = pre
标签:next span none 调整 += 复杂 col art rev
原文地址:https://www.cnblogs.com/latup/p/9864493.html