您的位置:首页 > 编程语言 > Go语言

[Leetcode Solution]Insertion Sort List

2014-03-21 13:19 423 查看
Insertion Sort is a basic sorting algorithm invented decades ago. And the implementation is simple, too.

Declare a head pointer of a sorted linked-list with initial value NULL. Then, add node to the new list one by one and keep the new list sorted.

class Solution {
public:
ListNode *insertionSortList(ListNode *head)
{
ListNode* res = NULL;
while (head) {
ListNode* next = head -> next;
insertion(&res, res, head);
head = next;
}
return res;
}

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