zoukankan      html  css  js  c++  java
  • 147 Insertion Sort List 链表插入排序

    用插入排序对链表进行排序。

    详见:https://leetcode.com/problems/insertion-sort-list/description/

    Java实现:

    链表的插入排序实现原理很简单,就是一个元素一个元素的从原链表中取出来,然后按顺序插入到新链表中,时间复杂度为O(n2),是一种效率并不是很高的算法,但是空间复杂度为O(1),以高时间复杂度换取了低空间复杂度。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode insertionSortList(ListNode head) {
            ListNode helper=new ListNode(-1);
            ListNode cur=helper;
            while(head!=null){
                ListNode next=head.next;
                cur=helper;
                while(cur.next!=null&&cur.next.val<=head.val){
                    cur=cur.next;
                }
                head.next=cur.next;
                cur.next=head;
                head=next;
            }
            return helper.next;
        }
    }
    
  • 相关阅读:
    excel的导入导出
    mybatis常用sql
    java中和时间相关的类,方法
    <resultMap>
    项目启动报的错
    多表查询
    file的一些方法
    AOV网络与AOE网络
    封装解封装过程
    以太网交换机
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8727445.html
Copyright © 2011-2022 走看看