# LeetCode-147 - Insertion Sort on Linked List

#### Insertion sort on linked list

Title description: Insertion sort on a linked list.

The animation of insertion sort is shown above. Starting from the first element, the linked list can be considered partially sorted (indicated in black).
At each iteration, an element (shown in red) is removed from the input data and inserted into the sorted linked list in place.

Insertion sort algorithm:

• Insertion sort is iterative, moving only one element at a time, until all elements can form an ordered output list.
• In each iteration, insertion sort removes only one element to be sorted from the input data, finds its proper position in the sequence, and inserts it.
• Repeat until all input data is inserted.

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode

###### Solution 1: Linked List Traversal
• First of all, if the linked list is empty or the linked list has only one node, it does not need to be sorted and returns directly.
• Otherwise, use the insertion sort method to put the nodes in the linked list into a List nodes;
• Then, reconstruct a new linked list in the order of nodes, which is the sorted linked list, and return it.
``````import com.kaesar.leetcode.ListNode;

import java.util.ArrayList;
import java.util.List;

public class LeetCode_147 {
public static ListNode insertionSortList(ListNode head) {
// 如果链表为空或者链表只有一个节点，则不用排序，直接返回
}
List<ListNode> nodes = new ArrayList<>();
while (cur != null) {
int i = nodes.size() - 1;
for (; i >= 0; i--) {
if (nodes.get(i).val < cur.val) {
break;
}
}
cur = cur.next;
}
for (int i = 1; i < nodes.size(); i++) {
cur.next = nodes.get(i);
cur = cur.next;
}
cur.next = null;

}

public static void main(String[] args) {

System.out.println("排序之前");
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
System.out.println();
System.out.println("排序之后");
while (cur != null) {
System.out.print(cur.val + " ");
cur = cur.next;
}
}
}``````
[Daily Message] I am afraid that everyone's life trajectory is predetermined in advance, but you have to work hard and believe that your destiny is in your own hands. People are not afraid of having ideals, and they are not afraid of how high or far the ideal is, as long as you stick to it , do not overestimate yourself, you will always succeed.

1.7k 声望
7.1k 粉丝
0 条评论