Insertion Sort List
很简单的一道题,思路跟数组的插入排序一样
/** * 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; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。