您的位置:首页 > 其它

LeetCode----Insertion sort list

2014-02-16 17:11 302 查看
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode *list)
{
ListNode *new_list(NULL), *next(NULL);
while(list)
{
next = list->next;
new_list = InsertNode(new_list, list);
list = next;
}
return new_list;
}
private:
ListNode* InsertNode(ListNode *list, ListNode *node)
{
//insert node into a sorted list
ListNode *pre(NULL), *cur(list);
while(cur && cur->val < node->val)
{
pre = cur;
cur = cur->next;
}
if(pre == NULL){
node->next = cur;
return node;
}
else{
node->next = cur;
pre->next = node;
}
return list;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: