- 暴力解法不再演示,使用一个列表将所有值保存下来,收尾双端遍历重新产生列表即可,读者自行编写。
大佬1:大佬用的递归,我是暂时没看懂,有空走代码看看。
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head or not head.next or not head.next.next:
return head
len_ = 0
p = head
while p:
len_ += 1
p = p.next
res = self.reorder_(head,len_)
return res
def reorder_(self,head,len_):
if len_ == 1:
tmp = head.next
head.next = None
return tmp
elif len_ == 2:
tmp = head.next.next
head.next.next = None
return tmp
tail = self.reorder_(head.next,(len_-2))
subhead = head.next
head.next = tail
tmp = tail.next
tail.next = subhead
return tmp