用插入排序对链表排序
样例
Given 1->3->2->0->null
, return 0->1->2->3->null
解题思路:另外建一个链表然后模拟排序插入即可。
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The head of linked list.
*/
ListNode *insertionSortList(ListNode *head) {
// write your code here
ListNode *t= new ListNode(0);
while(head!=NULL){
ListNode *pre=t;
while (pre->next != NULL && pre->next->val < head->val) {
pre = pre->next;
}
ListNode *tem=head->next;
head->next=pre->next;
pre->next=head;
head=tem;
}
return t->next;
}
};