题目地址:
https://leetcode.com/problems/insertion-sort-list/
插入排序一个链表。与数组的情况不同的是,数组里由于要批量移动元素,所以在寻找插入位置的时候,是从后向前找。而链表没办法也不需要从后向前找,所以每次只需要从头结点顺次下去找插入位置即可。代码如下:
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(0);
while (head != null) {
// 开始找第一个大于要插入节点的前一个节点
ListNode cur = dummy;
while (cur.next != null && cur.next.val < head.val) {
cur = cur.next;
}
// 先缓存一下链表的剩下部分
ListNode tmp = head.next;
// 执行插入
head.next = cur.next;
cur.next = head;
// 取出缓存的链表,然后继续遍历
head = tmp;
}
return dummy.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n 2 ) O(n^2) O(n2)。