147. Insertion Sort List

来源:互联网 发布:淘宝泳装模特 编辑:程序博客网 时间:2024/03/28 21:33

题目:

Sort a linked list using insertion sort.


题意:

使用插入排序排列链表


思路:

按照插入排序的算法,对链表进行轮询,将当前链表节点值与链表之前的部分进行对比,找到合适的位置进行插入。

代码:24ms

/** * 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) return head;                ListNode *dummy = new ListNode(-1);        ListNode *cur = head;        ListNode *prev = dummy;        ListNode *next = NULL;                while(cur){            next = cur->next;            if(!prev || !prev->next || prev->next->val>=cur->val) prev = dummy;            while(prev->next && prev->next->val<cur->val){                prev = prev->next;  //跳过小于当前节点值的部分            }            cur->next = prev->next;  //插入当前节点            prev->next = cur;            cur = next;        }        return dummy->next;    }};
代码:88ms

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

0 0