# 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 or not head.next:
return
mid=self.getmid(head)
r=self.reverse(mid.next)
mid.next=None
self.merge(head,r)
def getmid(self,head):
slow=head
fast=head.next
while fast and fast.next:
slow=slow.next
fast=fast.next.next
return slow
def reverse(self,head):
prev=None
while head:
tmp=head.next
head.next=prev
prev=head
head=tmp
return prev
def merge(self,l,r):
dummy=cur=ListNode(0)
while l and r:
cur.next=l
cur=l
l=l.next
cur.next=r
cur=r
r=r.next
if l:
cur.next=l
if r:
cur.next=r
# 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 or not head.next:
return
mid=self.getmid(head)
r=self.reverse(mid.next)
mid.next=None
self.merge(head,r)
def getmid(self,head):
slow=head
fast=head.next
while fast and fast.next:
slow=slow.next
fast=fast.next.next
return slow
def reverse(self,head):
prev=None
while head:
tmp=head.next
head.next=prev
prev=head
head=tmp
return prev
def merge(self,l,r):
dummy=cur=ListNode(0)
while l and r:
cur.next=l
cur=l
l=l.next
cur.next=r
cur=r
r=r.next
if l:
cur.next=l
if r:
cur.next=r