class ListNode():
def __init__(self,val):
self.val = val
self.next = None
class Solution():
def mergesortoflist(self,node):
if not node or not node.next:
return node
midnode = node
left = ListNode(0)
resL = left
right = ListNode(0)
resR = right
node = node.next
while node:
if midnode.val < node.val:
right.next = node
right = right.next
else:
left.next = node
left = left.next
node = node.next
left.next = None
right.next = None
L = self.mergesortoflist(resL.next)
R = self.mergesortoflist(resR.next)
midnode.next = R
if not L:
return midnode
else:
temp = L
while temp.next:
temp = temp.next
temp.next = midnode
return L