在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3 输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0 输出: -1->0->3->4->5
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
data = []
while head:
data.append(head.val)
head = head.next
data.sort()
ptr = ListNode(0)
ptr1 = ptr
for item in data:
ptr.next = ListNode(item)
ptr = ptr.next
return ptr1.next