力扣:147. 对链表进行插入排序

This commit is contained in:
huangge1199 2021-02-10 10:08:43 +08:00
parent bf4f350a47
commit 1f4206a2a2

View File

@ -0,0 +1,57 @@
package com.code.leet.study.t20210210;
import com.code.leet.entiy.ListNode;
/**
* 对链表进行插入排序
* <p>
* <p>
* 插入排序的动画演示如上从第一个元素开始该链表可以被认为已经部分排序用黑色表示
* 每次迭代时从输入数据中移除一个元素用红色表示并原地将其插入到已排好序的链表中
* <p>
*  
* <p>
* 插入排序算法
* <p>
* 插入排序是迭代的每次只移动一个元素直到所有元素可以形成一个有序的输出列表
* 每次迭代中插入排序只从输入数据中移除一个待排序的元素找到它在序列中适当的位置并将其插入
* 重复直到所有输入数据插入完为止
* <p>
* 来源力扣LeetCode
* 链接https://leetcode-cn.com/problems/insertion-sort-list
* 著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
*/
public class InsertionSortList {
/**
* 147. 对链表进行插入排序
*/
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode current = head.next;
head.next = null;
while (current != null) {
ListNode temp = head;
ListNode next = current.next;
current.next = null;
if (current.val < temp.val) {
head = current;
head.next = temp;
} else {
while (temp.next != null) {
if (current.val < temp.next.val) {
current.next = temp.next;
temp.next = current;
break;
} else {
temp = temp.next;
}
}
temp.next = temp.next == null ? current : temp.next;
}
current = next;
}
return head;
}
}