【LeetCode】147. Insertion Sort List C语言

来源:互联网 发布:怎样注册淘宝买家号 编辑:程序博客网 时间:2024/05/21 07:51
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* insertionSortList(struct ListNode* head) {    if(head == NULL) return head;        struct ListNode *dummy= (struct ListNode *)malloc(sizeof(struct ListNode));    dummy->next=NULL;           //new start of the sorted list        struct ListNode *pre=dummy; //insert node between pre and pre.next    struct ListNode *cur=head;  //the node will be inserted    struct ListNode *Next=NULL; //the next node will be inserted        while(cur != NULL)    {        Next=cur->next;        //find the right place to insert        while(pre->next != NULL && pre->next->val < cur->val)        {            pre=pre->next;        }        //insert between pre and pre.next        cur->next=pre->next;        pre->next=cur;                pre=dummy;        cur=Next;    }    return dummy->next;}

0 0
原创粉丝点击