Insertion Sort List(单链表插入排序)

来源:https://leetcode.com/problems/insertion-sort-list

Sort a linked list using insertion sort.

方法:

1. 使用一个preHead指向头节点,这样在将节点插入头节点前面时(即某个节点值比头节点小)不需要进行特殊处理

2. 从头节点开始遍历,如果当前节点的下一个节点的值比当前节点的值大,就从头开始遍历找到第一个比当前节点的下一个节点的值大的节点,并插入到它的前面,注意插入时需要同时处理节点移出位置和插入位置的指针。

 直接插入排序:

时间复杂度,平均O(n^2),最好O(1),此时节点本身有序,最坏O(n^2)

空间复杂度,需要的辅助存储为O(1)

稳定性,稳定,值相同的元素在排序后相对顺序保持不变

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode insertionSortList(ListNode head) {
11         ListNode preHead = new ListNode(0);
12         ListNode next = null, node = null, tmpNode = null;
13         preHead.next = head;
14         while(head != null) {
15             next = head.next;
16             if(next != null && next.val < head.val) {
17                 node = preHead;
18                 while(node.next != null && node.next.val <= next.val) {
19                     node = node.next;
20                 }
21                 tmpNode = node.next;
22                 node.next = next;
23                 head.next = next.next;
24                 next.next = tmpNode;
25             } else {
26                 head = head.next;
27             }
28         }
29         return preHead.next;
30     }
31 }// 8 ms
原文地址:https://www.cnblogs.com/renzongxian/p/7554016.html