描述:
Reverse a linked list from position m to n. Do it in-place and in one-pass.For example:
Given 1->2->3->4->5->nullptr, m = 2 and n = 4,
return 1->4->3->2->5->nullptr.Note:
Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
思路:对【m, n】区间的数进行头插法插入
代码如下:
# coding=utf-8
"""思路就是针对反转区间的数使用头插法,逻辑比较繁琐"""
class LinkNode(object): # 定义链表节点
def __init__(self, val, nextnode=None):
self.val = val
self.nextnode = nextnode
class Solution(object):
def reverse_between(self, linkroot=None, m=0, n=0):
root = LinkNode(0) # 处理反转起始位置为1,而增加一个节点
pre = root
pre.nextnode = linkroot
p = linkroot
t = m - 1
while t > 0: # pre 始终记录反转的起始位置的直接前驱
pre = p
p = p.nextnode # 始终保持指向反转的起始位置节点
t -= 1
cur = p # cur记录每次头插法的点
q = p.nextnode # q记录反转区间中的点
for _ in range(m + 1, n + 1): # 从反转起始的下一个点开始头插法
if q is not None:
r = q.nextnode # r记录q的直接后继节点
pre.nextnode = q
q.nextnode = cur
p.nextnode = r
cur = q
q = r
return root.nextnode
if __name__ == '__main__':
"""1->2->3->4->5->6->7->8->9 to 1->6->5->4->3->2->7->8->9"""
roota = LinkNode(1)
pp = roota
for i in range(2, 10):
qq = LinkNode(i)
pp.nextnode = qq
pp = pp.nextnode
root = Solution().reverse_between(roota, 2, 6)
while root is not None:
print root.val,
root = root.nextnode