Sort a linked list using insertion sort.
A:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode header = new ListNode(Integer.MIN_VALUE);
while(head!=null){
ListNode tmp = head;
head = head.next;
ListNode runner = header;
while(runner.next!=null && runner.next.val < tmp.val)
runner = runner.next;
tmp.next = runner.next;
runner.next = tmp;
}
return header.next;
}
}
Mistakes:
1: 当插入到比tail更前的的时候, 忘了break来跳出循环。
---------------第二遍--------------
1: 忘了把preNode 在whileloop的时候,先置为 newHeader
2: after checking preNode == null, Mistakenly wrote
tmp.next = preNode.next.next ; what the hell, can you make this mistake???????
Learned:
No comments:
Post a Comment