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;
}
}
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;
}
}
相关文章推荐
- Insertion Sort List
- LeetCode OJ Insertion Sort List
- leetcode day2 -- Sort List && Insertion Sort List
- leetcode 链表 Insertion Sort List
- Insertion Sort List--LeetCode
- Leetcode Insertion Sort List
- Insertion Sort List
- Insertion Sort List
- [LeetCode] Insertion Sort List
- Insertion Sort List
- 【LeetCode】Insertion Sort List
- LeetCode—Insertion Sort List 解题报告
- Leetcode习题:Insertion Sort List
- Insertion Sort List
- LeetCode OJ-- Insertion Sort List **
- insertion-sort-list
- Insertion Sort List
- list - insertion sort - AC
- 6.4 Insertion Sort List
- insertion sort list刷题 leetcode