用了两种方法求解。
第一种方法是非常容易求解的,新建一个list存放所有的listnode,然后用sorted()函数进行排序就行了,其中key取的是listnode的val,然后将排序好的listnode按照顺序连接起来就行。
第二种方法是使用归并排序,首先找到待排序的listnode的中间结点,然后将listnode从中间断开,变成两个listnode,对这两个sub listnode分别排序,排好了之后返回回来,得到两个有序的listnode,在对这两个有序的listnode进行merge,这个merge在前面写过好多次了,就是new两个指针,分别指向开头,然后cur不断指向小的那个node就行,这样就排序好了,最后返回merge之后的list。
代码如下:
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类 the head node
# @return ListNode类
#
class Solution:
def sortInList1(self , head: ListNode) -> ListNode:
# write code here
node_list = []
cur = head
while cur:
node_list.append(cur)
cur = cur.next
node_list = sorted(node_list , key = lambda x:x.val)
cur = head = ListNode(-1)
for i in range(len(node_list)):
cur.next = node_list[i]
cur = cur.next
cur.next = None
return head.next
def sortInList(self , head: ListNode) -> ListNode:
# 找到中间结点
if head.next == None or head == None:
return head
slow = fast = ListNode(-1)
slow.next = head
while True:
slow = slow.next
fast = fast.next.next
if fast == None or fast.next==None:
break
fast = slow.next
slow.next = None
head1 = head ; head2 = fast
head1 = self.sortInList(head1) ; head2 = self.sortInList(head2)
# 对两个子序列分别进行了排序,接下来要merge起来
text = cur = ListNode(-1)
p1 = head1 ; p2 = head2
while p1 or p2:
if p1==None:
cur.next = p2
p2=p2.next
elif p2==None:
cur.next = p1
p1 = p1.next
elif p1.val < p2.val:
cur.next = p1
p1 = p1.next
else:
cur.next = p2
p2=p2.next
cur = cur.next
return text.next
head = ListNode(1)
head.next = ListNode(3)
head.next.next = ListNode(2)
head = Solution().sortInList(head)
cur = head
while cur:
print(cur.val)
cur = cur.next