classSolution:definsertionSortList(self,head: ListNode) -> ListNode: ans =ListNode(float("-inf"))while head:next= head.next cur = answhile cur.next and cur.next.val < head.val: cur = cur.next head.next = cur.next cur.next = head head =nextreturn ans.next
Java Code:
classSolution {publicListNodeinsertionSortList(ListNode head) {ListNode ans =newListNode(-1);while( head !=null ){ListNode next =head.next;ListNode cur = ans;while(cur.next!=null&&cur.next.val<head.val ){ cur =cur.next; }head.next=cur.next;cur.next= head; head = next; }returnans.next; }}
JS Code:
varinsertionSortList=function (head) { ans =newListNode(-1);while (head !=null) { next =head.next; cur = ans;while (cur.next !=null&&cur.next.val <head.val) { cur =cur.next; }head.next =cur.next;cur.next = head; head = next; }returnans.next;};
CPP Code:
classSolution {public:ListNode*insertionSortList(ListNode* head) { ListNode dummy,*p;while (head) {auto*n = head; head =head->next; p =&dummy;while (p->next &&p->next->val <n->val) p =p->next;n->next =p->next;p->next = n; }returndummy.next; }};
复杂度分析
时间复杂度:$O(N^2)$,其中 N 为链表长度。
空间复杂度:$O(1)$。
大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 38K star 啦。大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。