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}.
题意:
给一个单链:L: L0→L1→…→Ln-1→Ln,
将它变成:L0→Ln→L1→Ln-1→L2→Ln-2→…
注意in-place,不要改变值,不需要返回值
思路:
在中间平均截开两段,若为奇数,则第一段多一个
将第二段reverse
然后两段再交错地link起来
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.
"""
if head is None or head.next is None or head.next.next is None:
head=head
else:
slow=fast=head # two parts
while fast.next and fast.next.next:
slow=slow.next
fast=fast.next.next
head2=slow.next
slow.next=None
dummy=ListNode(0) # reverse 2nd part
dummy.next=head2
p=head2.next
head2.next=None
while p:
tmp=p
p=p.next
tmp.next=dummy.next
dummy.next=tmp
head2=dummy.next
p1=head # rejoin 2 parts together
p2=head2
while p2:
t1=p1.next
p1.next=p2
t2=p2.next
p2.next=t1
p1=t1
p2=t2