目录
https://leetcode.com/problems/insertion-sort-list/
实现链表的插入排序
一、问题分析
测试用例:
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
将第一个节点作为已排序链表,第二个节点及后面的所有节点作为未排序链表,从左到右将未排序链表的每个节点插入已排序链表,同时保持已排序链表的有序性。具体的插入操作与数组的插入排序相反,每次寻找插入位置都需要从已排序的链表表头从左到右遍历,因为是单链表。
二、代码实现
1、迭代版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode tempHead = new ListNode(-1);
tempHead.next = head;
ListNode unsorted = head.next;
head.next = null;
while (unsorted != null) {
// System.out.println(unsorted.val);
// System.out.println(head.val +" "+ head.next.val +" "+ head.next.next.val +" "+
// head.next.next.next.val);
// 2
// 4 2 1 3
// 1
// 4 2 4 2
// 3
// 4 2 4 2
ListNode temp = unsorted.next;
unsorted.next = null;
ListNode cur = head;
//ListNode pre = null;
//java.lang.NullPointerException
ListNode pre = tempHead;
// while (cur != unsorted && cur.val <= unsorted.val) {
// Error - Found cycle in the ListNode
while (cur != null && cur.val <= unsorted.val) {
pre = cur;
cur = cur.next;
}
if (cur != null) {
//cur.val > unsorted.val && pre.val <= unsorted.val
unsorted.next = cur;
pre.next = unsorted;
}
// Error - Found cycle in the ListNode
else {
unsorted.next = null;
pre.next = unsorted;
}
head = tempHead.next; //输入:[4,2,1,3] 输出:[4]
unsorted = temp;
}
return head;
}
}
2、递归版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
//递归出口:
if (head == null || head.next == null) {
return head;
}
ListNode sorted = insertionSortList(head.next);
head.next = null;
//case 1:
if (head.val <= sorted.val) {
head.next = sorted;
return head;
}
//case 2:
ListNode pre = sorted;
while (pre.next != null && pre.next.val <= head.val) {
pre = pre.next;
}
// if (pre.next == null && pre.next.val <= head.val) {
if (pre.next == null) {
pre.next = head;
} else {
head.next = pre.next;
pre.next = head;
}
return sorted;
}
}
参考:
https://leetcode.com/problems/insertion-sort-list/discuss/46429/Thoughts-from-a-Google-interviewer
https://leetcode.com/problems/insertion-sort-list/discuss/46571/C%2B%2B-recursive-insertion-sort.
https://leetcode.com/problems/insertion-sort-list/discuss/46497/7ms-Java-solution-with-explanation
https://leetcode.com/problems/insertion-sort-list/discuss/46459/Accepted-Solution-using-JAVA