个人博客:https://luxialan.com

Insertion Sort List 分类: Leetcode(排序) 2015-04-09 11:26 23人阅读 评论(0) 收藏

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) {
        ListNode dummy(INT_MIN);
        
        for (ListNode * cur =head; cur != nullptr;) {
            ListNode * pos = findInsertPos(&dummy, cur->val);
            ListNode *tmp = cur->next;
            cur->next = pos->next;
            pos->next = cur;
            cur = tmp;
        }
        return dummy.next;
    
    }
    
    ListNode* findInsertPos(ListNode *head, int x) {
        ListNode *pre = nullptr;
        ListNode *cur =head;
        while(cur &&cur->val <=x) {
            pre = cur;
            cur = cur->next;
        }
        return pre;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-04-09 11:26  luxialan  阅读(136)  评论(0编辑  收藏  举报