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