LeetCode147 Insertion Sort List

题目链接:

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;
    }
};

你可能感兴趣的:(LeetCode,链表,插入排序,147)