LeetCode: Insertion Sort List

来源:互联网 发布:投影机的网络接口 编辑:程序博客网 时间:2024/05/16 08:35

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 || head->next == NULL)            return head;ListNode* cur = head->next;        ListNode* itr = head;        ListNode* pre = head;itr->next = NULL;        while(cur)         {itr = head;ListNode* next = cur->next;if(cur->val < itr->val){cur->next = itr;head = cur;}else{while(itr != NULL){if(cur->val >= itr->val){if(itr->next == NULL){itr->next = cur;cur->next = NULL;break;}else{pre = itr;itr = itr->next;}}else{pre->next = cur;cur->next = itr;break;}}}cur = next;        }        return head;    }};

Round 2:

class Solution {public:    ListNode *insertionSortList(ListNode *head) {        if(head == NULL || head->next == NULL)            return head;        ListNode *right = head->next;        head->next = NULL;        while(right != NULL)        {            ListNode *left = head;            ListNode *pre = NULL;            ListNode *next = right->next;            while(left != NULL && right->val > left->val)            {                pre = left;                left = left->next;            }            if(pre == NULL)            {                right->next = left;                head = right;            }            else            {                pre->next = right;                right->next = left;            }            right = next;        }        return head;    }};


Round 3:

/** * 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(NULL == head || NULL == head->next)            return head;        ListNode *right = head->next, *pre = NULL, *left = head;        head->next = NULL;        while(NULL != right)        {            ListNode *next = right->next;            if(right->val <= head->val)            {                right->next = head;                head = right;            }            else            {                ListNode *left = head;                while(NULL != left && right->val > left->val)                {                     pre = left;                     left = left->next;                }                if(left == NULL)                {                    pre->next = right;                    right->next = NULL;                }                else                {                    pre->next = right;                    right->next = left;                }            }            right = next;        }        return head;    }};


0 0
原创粉丝点击