/**注意往链表头插入元素的情况 * 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) { if((head==NULL)||(head->next==NULL)) return head; ListNode *res=head; head = head->next; res->next=NULL; while(head){ ListNode *p=res; while(p->next && (p->next->val) <= (head->val)){ p=p->next; } if((p->val) > (head->val)){ //这几个要注意顺序 ListNode *temp = head->next; head->next=p; res=head; head=temp; } else{ //注意顺序 ListNode *temp = p->next; p->next=head; head=head->next; p->next->next=temp; } } return res; } };