您的位置:首页 > 其它

Insertion Sort List

2014-02-19 23:40 295 查看
Sort a linked list using insertion sort.

public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}

// usding dummy head to simplify
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode curt = head.next;
head.next = null;

while (curt != null) {
ListNode nodeToInsert = curt;
curt = curt.next;
nodeToInsert.next = null;

// iterate sort list
ListNode prev = dummyHead;
ListNode n = dummyHead.next;
while (n != null) {
if (nodeToInsert.val <= n.val) {
prev.next = nodeToInsert;
nodeToInsert.next = n;
break;
} else {
prev = n;
n = n.next;
}
}
// 之前都没有比上,一直到 n == null
// attach 到 sort list 队尾
if (n == null) {
prev.next = nodeToInsert;
}
}
return dummyHead.next;
}


思路比较简单,就是用 insertion sort 的方法套用到 liked list 上。

一个新的node添加到队头的情况用 dummy head 可以方便地解决。

添加到队尾的情况就是对应于 (n == null),说明需要添加到队尾
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: