题目地址:
https://www.lintcode.com/problem/insertion-sort-list/description
插入排序一个链表。
另开一个函数写如何在一个有序链表里插入新节点。但尤其需要注意的是,不能失去对原链表的控制权。插入一个节点之前,要把剩余链表的表头记录下来,再插入。代码如下:
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
public ListNode insertionSortList(ListNode head) {
// write your code here
ListNode dummy = new ListNode(0);
while (head != null) {
head = insert(dummy, head);
}
return dummy.next;
}
// dummy是虚拟头结点。这个函数的功能是将节点cur插入到以dummy为虚拟头结点的链表中,
// 同时返回cur的后一个节点(也就是cur之后的原链表的表头)
private ListNode insert(ListNode dummy, ListNode cur) {
ListNode prev = dummy;
while (prev.next != null && prev.next.val < cur.val) {
prev = prev.next;
}
// 缓存一下剩余链表的表头
ListNode tmp = cur.next;
// 执行插入
cur.next = prev.next;
prev.next = cur;
// 把剩余链表的表头返回回去
return tmp;
}
}
class ListNode {
int val;
ListNode next;
ListNode (int x) {
val = x;
}
}
时间复杂度 O ( n 2 ) O(n^2) O(n2),空间 O ( 1 ) O(1) O(1)。