Insertion Sort List
生活随笔
收集整理的這篇文章主要介紹了
Insertion Sort List
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
插入排序是一種O(n^2)復(fù)雜度的算法,基本想法相信大家都比較了解,就是每次循環(huán)找到一個(gè)元素在當(dāng)前排好的結(jié)果中相對(duì)應(yīng)的位置,然后插進(jìn)去,經(jīng)過(guò)n次迭代之后就得到排好序的結(jié)果了。了解了思路之后就是鏈表的基本操作了,搜索并進(jìn)行相應(yīng)的插入。時(shí)間復(fù)雜度是排序算法的O(n^2),空間復(fù)雜度是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;} };
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔為你收集整理的Insertion Sort List的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Sort List
- 下一篇: Reorder List