LeetCode | Insertion Sort List

题目:

Sort a linked list using insertion sort.



思路:

常规的插入排序,直接上代码。


代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        if(head==NULL)
        {
            return NULL;
        }
        else
        {
            ListNode* cur = head->next;
            head->next = NULL;
            while(cur!=NULL)
            {
                ListNode* p = head;
                if(cur->val < p->val)
                {
                    head = cur;
                    cur=cur->next;
                    head->next=p;
                }
                else
                {
                    while(p!=NULL)
                    {
                        if(p->next ==NULL)
                        {
                            p->next = cur;
                            cur=cur->next;
                            p->next->next = NULL;
                            break;
                        }
                        else
                        {
                            if(cur->val < p->next->val)
                            {
                                ListNode* tmp = p->next;
                                p->next = cur;
                                cur=cur->next;
                                p->next->next = tmp;
                                break;
                            }
                            p=p->next;
                        }
                    }
                }
            }
            return head;
        }
    }
};

更加简洁的一个版本:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        ListNode* p = head;
        ListNode* result = new ListNode(0);
        while(p != NULL){
            ListNode* cur = p;
            p = p->next;
            insertSort(result, cur);
        }
        return result->next;
    }
    
    void insertSort(ListNode* head, ListNode* newNode){
        while(head->next != NULL){
            if(newNode->val < head->next->val){
                newNode->next = head->next;
                head->next = newNode;
                return;
            }
            head = head->next;
        }
        
        if(head->next == NULL){
            head->next = newNode;
            newNode->next = NULL;
        }
    }
};

    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17260611
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞