标签:
Sort a linked list using insertion sort.
/** * 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 || head.next==null) return head; ListNode newHead=new ListNode(0);//后面使用tmp.next与pre比较,所以增加一个新的newHead ListNode cur=head; while(cur!=null){ ListNode next=cur.next;//放这里而不放在循环末尾,防止out of index ListNode tmp=newHead; while(tmp.next!=null && tmp.next.val<cur.val){ tmp=tmp.next; } cur.next=tmp.next; tmp.next=cur; cur=next; } return newHead.next; } }
Leetcode 147. Insertion Sort List 插入排序 in Java
标签:
原文地址:http://www.cnblogs.com/yanyuqi/p/5851033.html