1 package leetcode; 2 3 class ListNode { 4 int val; 5 ListNode next; 6 7 ListNode(int x) { 8 val = x; 9 next = null; 10 } 11 } 12 13 public class insertionsortlist { 14 public static ListNode insertionSortList(ListNode head) { 15 ListNode h = new ListNode(0); 16 h.next = head; 17 ListNode pre = h; 18 ListNode be = head; 19 ListNode af; 20 ListNode po; 21 22 if(be==null||be.next==null) 23 return head; 24 af=be.next; 25 be.next=null; 26 while(af!=null){ 27 po=af.next; 28 pre=h; 29 be=h.next; 30 while (be != null && be.val <= af.val) { 31 pre = be; 32 be = be.next; 33 } 34 if(be==null){ 35 pre.next=af; 36 af.next=null; 37 }else{ 38 pre.next = af; 39 af.next = be; 40 } 41 af=po; 42 } 43 return h.next; 44 } 45 public static void main(String[] args) { 46 ListNode a = new ListNode(2); 47 ListNode b = new ListNode(1); 48 ListNode c = new ListNode(4); 49 a.next=b; 50 b.next = c; 51 c.next = null; 52 ListNode p = insertionSortList(a); 53 while (p != null) { 54 System.out.println(p.val); 55 p = p.next; 56 } 57 } 58 }