您的位置:首页 > 其它

leetcode -- Insertion Sort List

2013-11-16 22:10 405 查看
Sort a linked list using insertion sort.

public ListNode insertionSortList(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == null){
return head;
}
ListNode dummyHead = new ListNode(-2147483648);
ListNode p1 = dummyHead, p2 = head;

while(p2 != null){
ListNode pre = findInsertPlace(p1, p2);
// insert into list
// save orignal list next node
ListNode originalNext = p2.next;
p2.next = pre.next;
pre.next = p2;

p2 = originalNext;
}

return dummyHead.next;
}

public ListNode findInsertPlace(ListNode p1, ListNode p2){
ListNode pre = null, cur = p1;
while(cur != null && cur.val <= p2.val){
pre = cur;
cur = cur.next;
}
return pre;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: