zoukankan      html  css  js  c++  java
  • [Leetcode] Insertion Sort List

    Sort a linked list using insertion sort.

    Solution:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode insertionSortList(ListNode head) {
    14         if(head==null||head.next==null)
    15             return head;
    16         ListNode dummy=new ListNode(-1);
    17         ListNode pre,next;
    18         while(head!=null){
    19             pre=findPosition(dummy,head.val);
    20             next=pre.next;
    21             pre.next=new ListNode(head.val);
    22             pre.next.next=next;
    23             head=head.next;
    24         }
    25         return dummy.next;
    26     }
    27 
    28     private ListNode findPosition(ListNode dummy, int val) {
    29         // TODO Auto-generated method stub
    30         ListNode pre=dummy, next=pre.next;
    31         while(next!=null&&next.val<=val){
    32             next=next.next;
    33             pre=pre.next;
    34         }
    35         return pre;
    36     }
    37 }
  • 相关阅读:
    flex 自定义事件
    ssis 不停执行的方法
    动态修改大小的Panel用户控件
    ssis 写文件到数据库
    sqlserver CheckSum
    poj1423
    poj1860
    poj1862
    poj1426
    poj1234
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4102823.html
Copyright © 2011-2022 走看看