您的位置:首页 > 其它

LeetCode147 Insertion Sort List

2015-12-07 22:31 295 查看

题目链接:

https://leetcode.com/problems/insertion-sort-list/

题目描述:

对链表进行插入排序。

分析:

以前实现的都是数组的插入排序。想 一下链表其实也差不多的嘛。都是相当于摸一张牌,就把它排好在当前应该放的位置上。

代码:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息