leetcode 147 Insertion Sort List

Posted liuqiujie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 147 Insertion Sort List相关的知识,希望对你有一定的参考价值。

1. 

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode ln(0);ln.next=head;
        ListNode *pre=&ln,*cur=head;
        while(cur) {
            if(cur->next&&cur->next->val<cur->val) {
                while(pre->next&&pre->next->val<cur->next->val) pre=pre->next;
                ListNode *tmp=pre->next;
                pre->next=cur->next;
                cur->next=cur->next->next;
                pre->next->next=tmp;
                pre=&ln;
            }
            else cur=cur->next;
        }
        return ln.next;
    }
};

2. 

class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(!head||!head->next) return head;
        ListNode* cur=head->next,*pre=head;
        while(cur) {
            ListNode* comp=head,*prec=nullptr;
            while(comp&&comp->val<cur->val) {
                prec=comp;
                comp=comp->next;
                if(comp==cur) {
                    break;
                }
            }
            if(comp==cur) {
                pre=cur;
                cur=cur->next;
                continue;
            }
            if(!prec) {
                pre->next=cur->next;
                cur->next=head;
                head=cur;
                cur=pre->next;
            }
            else {
                pre->next=cur->next;
                prec->next=cur;
                cur->next=comp;
                cur=pre->next;
            }
        }
        return head;
    }
};

 

以上是关于leetcode 147 Insertion Sort List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-147-Insertion Sort List

LeetCode 147. Insertion Sort List

Leetcode 147. Insertion Sort List 插入排序 in Java

leetcode 147 Insertion Sort List

Leetcode147. Insertion Sort List

LeetCode 147. Insertion Sort List