- Insertion Sort List
Sort a linked list using insertion sort.
本题为单链表的插入排序,easy
ListNode* insertionSortList(ListNode* head) {
//本题很简单,是链表的插入排序
if(NULL == head || NULL == head->next)
{
return head;
}
ListNode* finalList = new ListNode(INT_MIN); //定义一个最终的链表用来保存最终的结果
while(head)
{
ListNode* pnode = head;
head = head->next;
ListNode* ppre = finalList;
ListNode* pnext = ppre->next;
while(pnext && pnext->val < pnode->val) //找到插入的位置
{
ppre = pnext;
pnext = pnext->next;
}
ppre->next = pnode;
pnode->next = pnext;
}
return finalList->next;
}