您的位置:首页 > 其它

[leetcode]Insertion Sort List

2014-07-21 14:50 399 查看
Insertion Sort List


Sort a linked list using insertion sort.



算法思路:

最基本的插入排序,时间复杂度O(n*n),空间复杂度O(1)

代码:

public class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode list = new ListNode(0);
list.next = head;
head = head.next;
list.next.next = null;
while(head != null){
ListNode tail = list;
ListNode node = head;
head = head.next;
node.next = null;
while(tail != null){
if(tail.next == null){
tail.next = node;
break;
}
if(tail.next.val > node.val){
node.next = tail.next;
tail.next = node;
break;
}else{
tail = tail.next;
}
}
}
return list.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: