我正在尝试构建一个有序链表,但不可能在新的有序列表中找到重复数据。假设 f_total
有以下值:
f_total:48 42 45 50 42 48 48 43
新的链表应该如下所示:
42 43 45 48 50
更新代码:
typedef struct _sigma {
int algo;
int f;
int c;
node_p list;
struct _sigma *next;
} sigma, *sigma_p;
sigma_p sigma_tmp = NULL;
sigma_p sigma_new = NULL;
sigma_p sigma_optimal = NULL;
int f_total = 0;
f_total = exectasks(m, nod_tmp, &c_max, &cmin); // f_total will be updated after each time exectasks function return.
...
if(sigma_optimal == NULL)
{
sigma_optimal = (sigma *)malloc(sizeof(sigma));
sigma_optimal->algo = 0;
sigma_optimal->f = f_optimal;
sigma_optimal->c = cmin;
sigma_optimal->list = nod_tmp;
sigma_optimal->next = NULL;
}
else
{
sigma_new = (sigma *)malloc(sizeof(sigma));
sigma_new->algo = 0;
sigma_new->f = f_optimal;
sigma_new->c = cmin;
sigma_new->list = nod_tmp;
sigma_tmp = sigma_optimal;
while(sigma_tmp != NULL && f_optimal > sigma_tmp->f)
{
sigma_prev = sigma_tmp;
sigma_tmp = sigma_tmp->next;
}
if(sigma_tmp != NULL)
{
if(sigma_tmp->f != f_optimal)
{
if(sigma_tmp == sigma_optimal)
{
sigma_new->next = sigma_optimal;
sigma_optimal = sigma_new;
}
else if(sigma_tmp->next == NULL)
{
sigma_prev->next = sigma_new;
sigma_new->next = sigma_tmp;
}
else if(sigma_tmp == NULL)
{
sigma_tmp->next = sigma_new;
sigma_new->next = NULL;
}
}
}
}
但这里我有两个问题:
- 列表的排序不正确。
- 它不会删除所有 重复。
最佳答案
最后我修复了它:
f_total = exectasks(m, nod_tmp, &c_max, &cmin); // f_total will be updated after each time exectasks function return.
...
if(sigma_optimal == NULL) // the start of the list
{
sigma_optimal = (sigma *)malloc(sizeof(sigma));
sigma_optimal->algo = 0;
sigma_optimal->f = f_optimal;
sigma_optimal->c = cmin;
sigma_optimal->list = nod_tmp;
sigma_optimal->next = NULL;
}
else
{
sigma_new = (sigma *)malloc(sizeof(sigma));
sigma_new->algo = 0;
sigma_new->f = f_optimal;
sigma_new->c = cmin;
sigma_new->list = nod_tmp;
sigma_tmp = sigma_optimal;
while(sigma_tmp != NULL && f_optimal > sigma_tmp->f)
{
sigma_prev = sigma_tmp;
sigma_tmp = sigma_tmp->next;
}
if(f_optimal != sigma_tmp->f && sigma_tmp != NULL)
{
if(sigma_tmp == sigma_optimal) // we are in the head
{
sigma_new->next = sigma_tmp;
sigma_optimal = sigma_tmp; // update the new head list
}
else // we are some where in the middle
{
sigma_prev->next = sigma_new;
sigma_new->next = sigma_tmp;
}
}
if(sigma_tmp == NULL) // we are in the end
{
sigma_prev->next = sigma_new;
sigma_new->next = NULL;
}
}
关于c - 插入有序链表并省略重复节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14595291/