Insertion Sort List

来源:互联网 发布:vb.net 高级编程 pdf 编辑:程序博客网 时间:2024/06/16 09:32

链表插入排序

插入排序的原理是,前半部分链表是有序的,遍历原链表,将每个节点插入到前面的有序链表中。

ListNode* insertionSortList(ListNode* head) {        if(head == NULL || head->next == NULL)        {            return head;        }        ListNode* p = head->next;        ListNode* p_next = NULL;        ListNode* sorted_list = head;        sorted_list->next = NULL;        while(p != NULL)        {            p_next = p->next;            sorted_list = insertOneNode(sorted_list, p);            p = p_next;         }        return sorted_list;    }   ListNode* insertOneNode(ListNode* head, ListNode* node)   {       ListNode* p = head;       ListNode* pre = NULL;       while(p != NULL)       {           if(p->val > node->val)           {               if(pre == NULL)               {                   node->next = head;                   return node;               }               else               {                   pre->next = node;                   node->next = p;                   return head;               }           }           pre = p;           p = p->next;       }       pre->next = node;       node->next = NULL;       return head;   }