Insertion Sort List
生活随笔
收集整理的這篇文章主要介紹了
Insertion Sort List
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
插入排序是一種O(n^2)復雜度的算法,基本想法相信大家都比較了解,就是每次循環找到一個元素在當前排好的結果中相對應的位置,然后插進去,經過n次迭代之后就得到排好序的結果了。了解了思路之后就是鏈表的基本操作了,搜索并進行相應的插入。時間復雜度是排序算法的O(n^2),空間復雜度是O(1)。
/*** 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) {ListNode* Head=new ListNode(NULL);ListNode* pre=Head;ListNode* cur=head;while(cur){ListNode* temp=cur->next;pre=Head;while(pre->next&&pre->next->val<cur->val ){pre=pre->next;}cur->next=pre->next;pre->next=cur;cur=temp;}return Head->next;} };
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的Insertion Sort List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Sort List
- 下一篇: Reorder List