您的位置:首页 > 其它

leetcode---insertion-sort-list---链表

2018-01-21 21:31 459 查看
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 *findPre(ListNode *head, int val)
{
ListNode *pre;
ListNode *cur = head;
while(cur && cur->val <= val)
{
pre = cur;
cur = cur->next;
}
return pre;
}

ListNode *insertionSortList(ListNode *head)
{
if(!head || !head->next)
return head;

ListNode *newH = new ListNode(INT_MIN);

while(head)
{
ListNode *next = head->next;
ListNode *pre = findPre(newH, head->val);
head->next = pre->next;
pre->next = head;
head = next;
}
return newH->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: