您的位置:首页 > 其它

Insertion Sort List

2015-08-09 11:52 204 查看
问题描述

Sort a linked list using insertion sort.

解决思路

1. 设置first和last指针;

2. 插入分三种情况。

程序

public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode dummy = new ListNode(-1);

ListNode first = null, last = null;
ListNode cur = head;

while (cur != null) {
ListNode next = cur.next; // save the next node
cur.next = null;

if (first == null || last == null) {
dummy.next = cur;
first = cur;
last = cur;
} else {
if (cur.val <= first.val) {
// insert before the first
dummy.next = cur;
cur.next = first;
first = cur;
} else if (cur.val >= last.val) {
// insert after last
last.next = cur;
last = cur;
} else {
// find the insert place
ListNode node = first;
while (node.next != null) {
if (node.next.val > cur.val) {
break;
}
node = node.next;
}
ListNode tmp = node.next;
node.next = cur;
cur.next = tmp;
}
}

cur = next;
}

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