链表的插入排序
1.注意插入的位置,表头,表中,表尾
2.排好序的那段链表的表尾指向哪,要处理好,要不然会超时
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
ListNode *ptr, *last, *p, *prev, *temp;
if(!head || head -> next == NULL)
return head;
last = head;
ptr = head -> next;
while(ptr){
if(ptr -> val < last -> val){
p = head;
while(ptr -> val >= p -> val){
prev = p;
p = p -> next;
}
if(p == head){
head = ptr;
}else{
prev -> next = ptr;
}
temp = ptr -> next;
ptr -> next = p;
last -> next = temp;//注意last->next的赋值
ptr = temp;
}else{
last = ptr;
ptr = ptr -> next;
}
}
last -> next = NULL;
return head;
}
};