Insertion Sort List
Sort a linked list using insertion sort.
Code:
class Solution { public: ListNode *insertionSortList(ListNode *head) { if(head==NULL) return head; ListNode *start=new ListNode(0); start->next=head; ListNode *pre=head; ListNode *cur=head->next; ListNode *nex; while(cur){ ListNode *p0=start; ListNode *p1=start->next; nex=cur->next; while(p1!=cur){ if(cur->val<p1->val){ p0->next=cur; cur->next=p1; pre->next=nex; break; } p0=p1; p1=p1->next; if(p1==cur) // if cur isn't removed, pre moves forward; If cur is removed, pre doesn't need to change. pre=cur; } cur=nex; } head=start->next; delete start; return head; } };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步