20.11.20 leetcode147
题目链接:https://leetcode-cn.com/problems/insertion-sort-list/
题意:对一个链表进行选择排序
分析:直接就是O(n^2)的做法,从头到尾遍历
/** * 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) { if( head== nullptr )return head; ListNode* dummyHead=new ListNode(0); dummyHead->next=head; ListNode* sortedNode=head,* curr=head->next; while(curr!=nullptr){ if(sortedNode->val<=curr->val)sortedNode=sortedNode->next; else{ ListNode* pre=dummyHead; while(pre->next->val<=curr->val)pre=pre->next; sortedNode->next=curr->next; curr->next=pre->next; pre->next=curr; } curr=sortedNode->next; } return dummyHead->next; } };