题目

Sort a linked list using insertion sort.
0147. Insertion Sort List (M) - 图1
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.

Example 1:

  1. Input: 4->2->1->3
  2. Output: 1->2->3->4

Example 2:

  1. Input: -1->5->3->4->0
  2. Output: -1->0->3->4->5

题意

对给定的链表进行插入排序。

思路

遍历原链表,每次将当前结点从原链表中取出,插入到新链表对应的位置即可。


代码实现

Java

  1. class Solution {
  2. public ListNode insertionSortList(ListNode head) {
  3. ListNode dummy = new ListNode(0);
  4. while (head != null) {
  5. // 将每一个原结点断开并取出
  6. ListNode p = head;
  7. head = head.next;
  8. p.next = null;
  9. // 插入到新链表中
  10. ListNode pre = dummy, cur = dummy.next;
  11. while (cur != null && cur.val < p.val) {
  12. cur = cur.next;
  13. pre = pre.next;
  14. }
  15. p.next = cur;
  16. pre.next = p;
  17. }
  18. return dummy.next;
  19. }
  20. }

JavaScript

  1. /**
  2. * @param {ListNode} head
  3. * @return {ListNode}
  4. */
  5. var insertionSortList = function (head) {
  6. let dummy = new ListNode()
  7. while (head) {
  8. let node = head
  9. head = head.next
  10. node.next = null
  11. let pre = dummy
  12. let cur = dummy.next
  13. while (cur && cur.val < node.val) {
  14. cur = cur.next
  15. pre = pre.next
  16. }
  17. node.next = cur
  18. pre.next = node
  19. }
  20. return dummy.next
  21. }