Insertion Sort List
Sort a linked list using insertion sort.
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(NULL == head) return NULL;
ListNode *ptr = head->next, *q;
ListNode *nhead = head; //新的头结点指针
ListNode *tptr = nhead;
nhead->next = NULL;
while(ptr){
q = ptr;
ptr = ptr->next;
if(q->val <= nhead->val){ //如果当前结点值 比头指针值还小 作为新的头指针
q->next = nhead;
nhead = q;
continue;
}
tptr = nhead;
while(tptr->next){ //使用tptr->next是因为要记录前一结点的指针
if(tptr->next->val >= q->val) break;
tptr = tptr->next;
}
q->next = tptr->next;
tptr->next = q;
}
return nhead;
}
};