您的位置:首页 > 其它

Insertion Sort List

2015-04-27 21:56 309 查看
Sort a linked list using insertion sort.

public class Whynot {
public ListNode insertionSortList(ListNode head) {
if (head == null){
return null;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = head;
ListNode p = head.next;
ListNode h;
while (p != null) {
h = dummy; //每次循环都将h重新赋值为头结点,将p依次与h.next进行比较
while (h.next != p) {
if (h.next.val < p.val) {
h = h.next;
} else { //若当前h.next比p值大,则将p插入h与h.next之间
pre.next = p.next;
p.next = h.next;
h.next = p;
p = pre; //插入之后,将当前pre赋给p,继续循环
break;
}
}
pre = p;
if (p != null) {
p = p.next;
}
}
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: