题意:

image.png

解题思路:

  1. 思路:[遍历n个节点,每个节点遍历n次,时间复杂度O(n2)]
  2. 1. 定义虚拟dummy节点,指向头节点,定义头节点为cur
  3. 2. 扫描链表,前后节点进行比较,如果前面元素u小于后面p->nextv,则需要把u插入到p后面,v前面:p->next = 2 ,插入0 => [p->next = 0, 0->next = 2] => p->0->2;
  4. 3. 直到最后节点为空退出;

PHP代码实现:

  1. /**
  2. * Definition for a singly-linked list.
  3. * class ListNode {
  4. * public $val = 0;
  5. * public $next = null;
  6. * function __construct($val) { $this->val = $val; }
  7. * }
  8. */
  9. class Solution {
  10. /**
  11. * @param ListNode $head
  12. * @return ListNode
  13. */
  14. function insertionSortList($head) {
  15. $dummy = new ListNode(0);
  16. $cur = $head;
  17. while ($cur != null) {
  18. $next = $cur->next;
  19. $p = $dummy;
  20. while ($p->next != null && $cur->val >= $p->next->val) {
  21. $p = $p->next;
  22. }
  23. $cur->next = $p->next;
  24. $p->next = $cur;
  25. $cur = $next;
  26. }
  27. return $dummy->next;
  28. }
  29. }

GO代码实现:

  1. /**
  2. * Definition for singly-linked list.
  3. * type ListNode struct {
  4. * Val int
  5. * Next *ListNode
  6. * }
  7. */
  8. func insertionSortList(head *ListNode) *ListNode {
  9. dummy := &ListNode{}
  10. cur := head
  11. for cur != nil {
  12. next := cur.Next
  13. p := dummy
  14. for p.Next != nil && cur.Val >= p.Next.Val {
  15. p = p.Next
  16. }
  17. cur.Next = p.Next
  18. p.Next = cur
  19. cur = next
  20. }
  21. return dummy.Next
  22. }