自己1:本来想采用单次从原链表中拆除出一个节点然后插入到新链表中相应位置的方式,但是超出了时间限制。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from copy import deepcopy
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
#设立头结点
head_ = ListNode(-1)
tail = head_
p = head
while p:
#拆下单个节点
tmp_node = deepcopy(p)
tmp_node.next = None
print(tmp_node)
print(head_)
if head_.next != None:
flag = False
pre_c = head_
c = head_.next
while c:
print(1)
if tmp_node.val <= c.val:
tmp_node.next = c
pre_c.next = tmp_node
flag = True
p = p.next
break
else:
c = c.next
pre_c = pre_c.next
if not flag:
tail.next = tmp_node
tail = tail.next
p = p.next
else:
head_.next = tmp_node
tail = head_.next
p = p.next
return head_.next
大佬1:大佬用递归来做,但是还是超出了时间限制,可见递归耗时啊
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from copy import deepcopy
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
res = ListNode(-1)
p = head
while p:
next = p.next
res.next = self.insert(res.next,p)
p = next
return res.next
def insert(self,head,node):
if not head or head.val >node.val:
node.next = head
return node
head.next = self.insert(head.next, node)
return head
大佬2:采用头插法不断将比头结点小的值插入进来,感觉是选择排序,并不是插入,怎操蛋
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from copy import deepcopy
class Solution(object):
def insertionSortList(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