首页 > 编程语言 > 详细

算法-插入排序链表

时间:2020-06-05 10:11:07      阅读:52      评论:0      收藏:0      [点我收藏+]
/**
 * 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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!