147. Insertion Sort List

来源:互联网 发布:潜韵耳机的官方淘宝店 编辑:程序博客网 时间:2024/04/27 03:04

Sort a linked list using insertion sort.

题意:对链表进行插入排序。

思路:每次对tail之后的结点操作,并适当更新tail(或head)。

class Solution {public:ListNode* insertionSortList(ListNode* head) {if (head == NULL)return head;ListNode* tail = head;ListNode* q = tail->next;while (q){//extracttail->next = q->next;//searchListNode* tmp = head;if (tmp->val >= q->val){q->next = tmp;head = q;}else{while (tmp != tail && tmp->next->val < q->val){tmp = tmp->next;}q->next = tmp->next;tmp->next = q;if (tmp == tail)tail = q;}//go onq = tail->next;}return head;}};

二刷:链表的操作,设置一个dummy会好一些。插入排序,不能从后向前走,因为链表是单向的,所以每次要从头往后找。因此设置一个dummy就会方便很多。

class Solution {public:ListNode* insertionSortList(ListNode* head) {ListNode *dummy = new ListNode(0);ListNode *cur = head;while (cur){ListNode *tmp = cur->next;insert(dummy, cur);cur = tmp;}return dummy->next;}private:void insert(ListNode *dummy, ListNode* cur){ListNode *pre = dummy;while (pre->next && pre->next->val < cur->val)pre = pre->next;ListNode *tmp = pre->next;pre->next = cur;cur->next = tmp;}};





0 0
原创粉丝点击