您的位置:首页 > 其它

LeetCode 147. Insertion Sort List

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