"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def insertionSortList(self, head):
# write your code here
if head.next is None:return head
prehead = head #定义temp为拟排序节点
temp = head.next
if temp is not None:prenext = temp.next
else:prenext = None
flag = 0 #标记是否对temp做了排序
while temp:
nowhead = head #定义nownode 为对比节点
nownode = head.next
if temp.val < head.val: #首先对比head的值进行判断
temp.next = head
head = temp
temp = prenext
prehead.next = prenext
if temp is not None:prenext = temp.next
else:prenext = None
continue
while nownode != temp: #然后循环对比temp前的所有节点
if temp.val < nownode.val:
flag = 1
nowhead.next = temp
temp.next = nownode
prehead.next = prenext
temp = prenext
if temp is not None:prenext = temp.next
else:prenext = None
break
else:
nowhead = nownode
nownode = nownode.next
if flag == 0:
prehead = temp
temp = prenext
if temp is not None:prenext = temp.next
else:prenext = None
flag = 0
return head
lintcode 173 单链表插入排序 python
最新推荐文章于 2022-01-06 16:19:22 发布