思路:新建一个链表, 遍历原链表,将节点插入新链表正确的位置上面
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.List;
import java.util.LinkedList;
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(-1);
while(head != null){
//定义一个指针节点,找到当前节点在新链表中的正确位置
ListNode node = dummy;
while(node.next != null && node.next.val < head.val){
node = node.next;
}
//记录head.next
ListNode temp = head.next;
head.next = node.next;
node.next = head;
//恢复head.next
head = temp;
}
return dummy.next;
}
}