题目
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
思路
三部曲思路,很直接
- 把list拆成前半段和后半段
- 把后半段reverse
- 把后半段依次插入前半段的相应位置(在148中学到的)
Python
# 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.
"""
#3 step methods. 1.find the mid. 2.Reverse the second half. 3.insert one buy one
if not head or not head.next: return #basecase
#First step, find mid
slow = fast = head
while fast and fast.next:
# pre = slow
slow = slow.next
fast = fast.next.next
shalf = slow.next
slow.next = None #make head to be the first half
#reverse the second half
r_shalf = None
while shalf:
temp = shalf.next
shalf.next = r_shalf
r_shalf = shalf
shalf = temp
#insert the second half to the first half one buy one.
node = head
while r_shalf:
temp = r_shalf.next
r_shalf.next = node.next
node.next = r_shalf
r_shalf = temp
node = node.next.next