zoukankan      html  css  js  c++  java
  • leetcode -- Insertion Sort List

    Sort a linked list using insertion sort.

     1 public ListNode insertionSortList(ListNode head) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         if(head == null){
     5             return head;
     6         }
     7         ListNode dummyHead = new ListNode(-2147483648);
     8         ListNode p1 = dummyHead, p2 = head;
     9         
    10         while(p2 != null){
    11             ListNode pre = findInsertPlace(p1, p2);
    12             // insert into list
    13             // save orignal list next node
    14             ListNode originalNext = p2.next;
    15             p2.next = pre.next;
    16             pre.next = p2;
    17             
    18             p2 = originalNext;
    19         }
    20         
    21         return dummyHead.next;
    22     }
    23     
    24     public ListNode findInsertPlace(ListNode p1, ListNode p2){
    25         ListNode pre = null, cur = p1;
    26         while(cur != null && cur.val <= p2.val){
    27             pre = cur;
    28             cur = cur.next;
    29         }
    30         return pre;
    31     }
  • 相关阅读:
    day06
    day05
    day04
    day03
    day02
    day01
    python-study-42
    OI 知识总览 算法篇 之 图论
    OI 知识总览 算法篇 之 基础算法
    [CSP2019-JX] 散步 解题报告
  • 原文地址:https://www.cnblogs.com/feiling/p/3427232.html
Copyright © 2011-2022 走看看