0
我最近接到一个挑战,要编写一个有效,优雅的C函数,它将无序链接列表的内容插入到有序的链表。将无序链接列表插入到有序链接列表中
这是我想出了:
node * insert(node * dest, node * src)
{
node * current = dest;
node * previous = NULL;
//Deal with zero-length destination list
if (dest == NULL) { return src; }
//Deal with putting it at the start
if (src->data >= dest->data)
{
src->next = dest;
return src;
}
//Iterate to find the right position
while (current->data <= src->data)
{
previous = current;
current = current->next;
}
previous->next = src;
src->next = current;
return dest;
}
node * insertLL(node * sorted, node * unsorted)
{
while(unsorted != NULL)
{
node * next_unsorted = unsorted->next;
sorted = insert(sorted, unsorted);
unsorted = next_unsorted;
}
return sorted;
}
大家可以批评我的功能 - 我的插入()函数,尤其是是否是有效的?这对我来说似乎相当大。
按**命令**你其实是指**排序**吗?因为链表总是有序的(它们的元素总是按照某种顺序)。 – Jesper 2011-06-16 07:07:27