Sort a linked list using insertion sort.
思路:插入排序,从今天起,养成良好的编程风格
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode* pre = new ListNode(0);
ListNode* p = pre;
p->next = head;
ListNode* end = head;
ListNode* cur = head ->next;
ListNode* tmp = cur;
while (cur != nullptr){
p = pre;
while (p!=end && p->next->val < cur->val){
p = p->next;
}
if (p != end){
tmp = p->next;
end->next = cur->next;
p->next = cur;
cur->next = tmp;
cur = end->next;
}
else{
end = cur;
cur = cur->next;
}
}
return pre->next;
delete pre;
}
};