【发布时间】:2011-06-16 06:51:09
【问题描述】:
我最近遇到了一个挑战,要编写(一个)高效、优雅的 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;
}
你们都可以批评我的函数吗?尤其是我的 insert() 函数是否有效?对我来说似乎相当大。
【问题讨论】:
-
您所说的ordered是指sorted吗?因为链表总是有序的(它们的元素总是按某种顺序排列的)。
标签: c linked-list