/** * 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 tmpHead = insertionSortList(head.next); if(head.val <= tmpHead.val){ // 如果两个节点相等,则插入到已存在节点的前面 head.next = tmpHead; return head; }else{ ListNode tmpHead2 = tmpHead; // 找到合适的位置的前一个节点 while(tmpHead2.next != null && tmpHead2.next.val < head.val){ tmpHead2 = tmpHead2.next; } // 将head连接到链表中 ListNode b = tmpHead2.next; tmpHead2.next = head; head.next = b; return tmpHead; } } }
原文:https://www.cnblogs.com/caiyao/p/13047837.html