147. Insertion Sort List

来源:互联网 发布:淘宝自制食品怎么上架 编辑:程序博客网 时间:2024/04/16 22:18

Sort a linked list using insertion sort.

Subscribe to see which companies asked this question

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode insertionSortList(ListNode head) {        if(head==null)return head;        ListNode a = new ListNode(0);        a.next=head;        ListNode cur = head;        ListNode pre = head.next;        if(pre==null)return head;        // ListNode last= head;        cur.next=null;        while(pre!=null){            cur=pre;            pre=pre.next;            cur.next=null;            if(a.next.val>=cur.val){                cur.next=a.next;                a.next=cur;            }else{                ListNode tem = a.next;                ListNode temLast = tem;                tem=tem.next;                while(tem!=null){                    if(tem.val>=cur.val){                        temLast.next=cur;                        cur.next=tem;                        break;                    }else{                        temLast=tem;                        tem=tem.next;                    }                }                if(tem==null){                    temLast.next=cur;                }            }        }        return a.next;    }}

0 0
原创粉丝点击