问题描述
- Sort a linked list using insertion sort.
- 地址
问题分析
- 该题是在链表上实现插入排序。
- 具体做法为,新建一个空链表,然后从原链表中每次取出一个节点,然后从前到后遍历新链表,找到待插入的位置,将该节点插入到新链表中。 注意,与反转部分链表的不同,这个是取出一个节点!!!
代码实现
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0);
ListNode insertNode = head;
ListNode nextInsert = null;
ListNode curNode = dummy;
while (insertNode != null) {
nextInsert = insertNode.next;
curNode = dummy;
while (curNode.next != null && curNode.next.val < insertNode.val) {
curNode = curNode.next;
}
insertNode.next = curNode.next;
curNode.next = insertNode;
insertNode = nextInsert;
}
return dummy.next;
}