边工作边刷题:70天一遍leetcode: day 10-2
Reorder List
要点:算法直观不多讲,这题就是实现有些细节要注意
- 同样是前面提到的slow和fast的算法最终slow落在奇数结点中点或者偶数结点的中间右侧。所以第二步reverse的起点是slow.next:奇数很明显,偶数个,右面list的第一个结点是reverse后的最后一个结点,是不移动的
- reverse前一定不要忘了把前后两个list分开(即set slow.next=None),否则后一个list在reverse后是没有null end的
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head: return
fast = slow = head
while fast:
fast=fast.next
if fast:
fast=fast.next
slow=slow.next
#print fast.val, slow.val
if not slow.next: return
cur = slow.next
pre = None
slow.next = None
while cur:
next = cur.next
cur.next = pre
pre = cur
cur = next
first = head
second = pre
print first.val,second.val
while first and second:
next = second.next
#print next.val
second.next = first.next
first.next = second
first = second.next
second = next