题目链接:
题目描述:
对链表进行插入排序。
分析:
以前实现的都是数组的插入排序。想 一下链表其实也差不多的嘛。都是相当于摸一张牌,就把它排好在当前应该放的位置上。
代码:
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* pHead=(ListNode*)malloc(sizeof(ListNode));
pHead->next=head;
ListNode* pre1=pHead;
ListNode* cur=head;
while(cur!=NULL){
ListNode* pre2=pHead;
ListNode* ptr=pHead->next;
bool flag=false;
while(ptr!=cur){
if(cur->val<ptr->val){
flag=true;
break;
}
pre2=ptr;
ptr=ptr->next;
}
if(flag){
pre1->next=cur->next;
pre2->next=cur;
cur->next=ptr;
cur=pre1->next;
}
else{
pre1=cur;
cur=cur->next;
}
}
return pHead->next;
}
};