您的位置:首页 > 其它

Leetcode习题:Insertion Sort List

2013-12-25 22:52 441 查看


Insertion Sort List

Total Accepted: 2832 Total
Submissions: 11108My Submissions

Sort a linked list using insertion sort.
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) {
return null;
}

ListNode p1 = head.next;
head.next = null;

while (p1 != null) {
ListNode prev = null;
ListNode p2 = head;
while (p2!=null && p2 != p1 && p2.val < p1.val) {
prev = p2;
p2 = p2.next;
}

ListNode next = p1.next;

if(p2 == null){
prev.next = p1;
p1.next = null;
}else if (prev == null) {// head
p1.next = head;
head = p1;
}else {
p1.next = prev.next;
prev.next = p1;
}
p1 = next;
}

return head;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: