对一个链表的插入排序

来源:互联网 发布:北bi数据分析 编辑:程序博客网 时间:2024/05/21 15:46
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* insertionSortList(struct ListNode* head) {
    
    struct ListNode *node=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* cur;
    struct ListNode* tmp;
    struct ListNode* pre;
    struct ListNode* end;
    node->next=head;
    if(head!=NULL&&head->next!=NULL){
        cur=head->next;
        end=head;
        while(cur!=NULL){
            pre=node;
            if (cur->val>=end->val){
                end=cur;
            }
            else{
                while(cur->val>=pre->next->val){
                    pre=pre->next;
                }
                tmp=pre->next;
                end->next=cur->next;
                pre->next=cur;
                cur->next=tmp;
            }
            cur=end->next;
        }
    }
    return node->next;
}
0 0