自己1:暴力破解法
# 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
"""
if not head:
return None
num_list = list()
p = head
while p:
num_list.append(p.val)
p = p.next
num_list.sort()
head_ = ListNode(-1)
p = head_
for i in num_list:
tmp = ListNode(int(i))
p.next = tmp
p = p.next
return head_.next
自己2:节点头插法:想法是对的,不过在大量数据的情况下,消耗的时间也是比较长的,超出了时间限制。
# 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
"""
if not head:
return None
head_ = ListNode(-1) #新增表头节点
head_.next = head
p = head.next #保留当前节点的第一个节点,用于比较
head.next = None
while p:
curr = p.next #保存下一个节点信息
q = head_ #设立头结点指针,每次都要循环判断
while q.next and q.next.val <= p.val:#一直循环找比当前头结点值小的节点
q = q.next
p.next = q.next #头插法插入节点
q.next = p #当前值比所有元素都大,所以要放在最后
p = curr #后移
return head_.next