147. Insertion Sort List

来源:互联网 发布:爱淘宝怎么删除 编辑:程序博客网 时间:2024/06/16 02:51

这道题要求用插入排序法给一个链表排序。

这道题我写的很麻烦,但是一次就AC了。我维护两个链表,一个是已经排好了的一部分,一个是待排序的一部分。然后把待排序的那部分一个个插入。

/** * 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* pre = NULL, *tail = NULL, *cur = head;        while(cur){            if(pre == NULL){                pre = cur;                tail = cur;                cur = cur->next;                tail->next = NULL;            }else{                if(cur->val >= tail->val){                    tail->next = cur;                    tail = cur;                    cur = cur->next;                    tail->next = NULL;                }else if(cur->val <= pre->val){                    ListNode* curnext = cur->next;                    cur->next = pre;                    pre = cur;                    cur = curnext;                }else{                    ListNode* insert = pre;                    while(insert->next->val < cur->val){                        insert = insert->next;                    }                    ListNode* insertnext = insert->next;                    ListNode* curnext = cur->next;                    insert->next = cur;                    cur->next = insertnext;                    cur = curnext;                }            }        }        return pre;    }};
看别人的简单的代码:

/** * 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 *res = new ListNode(-1);        ListNode *cur = res;        while (head) {            ListNode *next = head->next;            cur = res;            while (cur->next && cur->next->val <= head->val) {                cur = cur->next;            }            head->next = cur->next;            cur->next = head;            head = next;        }        return res->next;    }};


原创粉丝点击