zoukankan      html  css  js  c++  java
  • 147. Insertion Sort List

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode insertionSortList(ListNode head) {
    11         if(head==null) return head;//corner case:if the List is null;
    12         ListNode helper = new ListNode(0);
    13         ListNode pre = helper,//insert between pre and pre.next
    14         cur = head,//the node will be inserted
    15         next = null;//the next node will be valued by cur
    16         while(cur!=null){
    17             next = cur.next;
    18             // find the right place to insert
    19             while(pre.next!=null&&pre.next.val<cur.val){
    20                 pre=  pre.next;
    21             }
    22             // insert between pre and pre.next
    23             cur.next = pre.next;
    24             pre.next = cur;
    25             pre = helper;
    26             cur = next;
    27         }
    28         return helper.next;
    29     }
    30 }
    31 // as for the run time complexity,for the worst case, it will cost O(n^2) time. As for the space complexity,it will take O(n) 
  • 相关阅读:
    线程池
    交互
    Java类文件的结构详细介绍
    redis
    弹幕
    约瑟夫环问题
    Redis数据类型和应用场景
    Java集合类整体结构
    JDBC详细介绍
    Mybatis万能Map
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6361034.html
Copyright © 2011-2022 走看看