题目链接
思路:
数组的插入排序需要每次从排好序的尾部开始与当前元素进行比较,但单链表无法反向遍历,只能每次都从头开始逐个遍历节点。
每次从链表上取下来一个节点,在当前已排好序的链表中进行查找比它大的节点,并记录这个节点的前一个节点,然后将此节点插入其中即可。
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 准备一个哑节点,方便操作
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = head.next;
// 将头节点与链表断开
head.next = null;
ListNode pre = dummy;
ListNode next = null;
// 当前节点不空,说明未遍历结束
while (cur != null) {
pre = dummy;
// 取下当前节点
next = cur.next;
cur.next = null;
// 在排序好的链表中查找插入位置
while (pre.next != null && pre.next.val <= cur.val) {
pre = pre.next;
}
// 若插入位置不是链尾
if (pre.next != null) {
cur.next = pre.next;
}
pre.next = cur;
cur = next;
}
return dummy.next;
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}