您的位置:首页 > 其它

[leetcode]147. Insertion Sort List

2017-07-25 18:02 363 查看
题目链接:https://leetcode.com/problems/insertion-sort-list/#/description

Sort a linked list using insertion sort.class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* new_head = new ListNode(0);
new_head -> next = head;
ListNode* pre = new_head;
ListNode* cur = head;
while (cur) {
if (cur -> next && cur -> next -> val < cur -> val) {
while (pre -> next && pre -> next -> val < cur -> next -> val)
pre = pre -> next;
/* Insert cur -> next after pre.*/
ListNode* temp = pre -> next;
pre -> next = cur -> next;
cur -> next = cur -> next -> next;
pre -> next -> next = temp;
/* Move pre back to new_head. */
pre = new_head;
}
else cur = cur -> next;
}
ListNode* res = new_head -> next;
delete new_head;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: