您的位置:首页 > 其它

LeetCode (Insertion Sort List)

2017-07-10 15:49 316 查看
Problem:

Sort a linked list using insertion sort.

Solution:

/**
* 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 || !head->next) return head;
ListNode l(0), *pre = &l;
ListNode *cur = head, *next;
while(cur){
next = cur->next;
while(pre->next && pre->next->val < cur->val)
pre = pre->next;
cur->next = pre->next;
pre->next = cur;
cur = next;
pre = &l;
}
return l.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: