【LintCode 简单】173. 链表插入排序

待我称王封你为后i 2022-06-01 11:49 285阅读 0赞

1.问题描述:

用插入排序对链表排序。

2.样例:

Given 1->3->2->0->null, return 0->1->2->3->null

``

3.代码:

``

  1. """
  2. Definition of ListNode
  3. class ListNode(object):
  4. def __init__(self, val, next=None):
  5. self.val = val
  6. self.next = next
  7. """
  8. class Solution:
  9. """
  10. @param: head: The first node of linked list.
  11. @return: The head of linked list.
  12. """
  13. def insertionSortList(self, head):
  14. # write your code here
  15. if head is None:
  16. return None
  17. if head.next is None:
  18. return head
  19. l=ListNode(-9999)
  20. while head:
  21. node=l
  22. fol=head.next
  23. while node.next and node.next.val < head.val:
  24. node = node.next
  25. head.next = node.next
  26. node.next = head
  27. head = fol
  28. return l.next

发表评论

表情:
评论列表 (有 0 条评论,285人围观)

还没有评论,来说两句吧...

相关阅读

    相关 插入排序算法

    如果数据存储在一段连续的内存上,比如数组中,插入排序算法的实现相信大家都已经非常熟悉,如果要对一个单链表进行插入排序,将会牵扯到大量指针操作。 同时,如果在实现的过

    相关 LintCode 简单】96. 划分

    1.问题描述: 给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。 你应该保留两部分内链表节点原有的相对顺序。 2.样例: 给定链