【发布时间】:2023-01-08 23:19:49
【问题描述】:
问题如下。我想要一个函数,给定一个列表和最大出现次数“x”,删除列表中出现超过 x 次或 x 次的所有元素。
我找到了一个非常简单的解决方案,即检查每个元素。这就是说,多次重复查找和删除功能似乎在计算方面对我来说不是最佳选择。
我想知道你是否可以提供一个更好的算法(我排除了从最小到最大的矩阵分配内存......对于任务来说太多了......假设你有很少的非常大的数字并且你的内存不会做它。)
我的代码如下。
typedef struct n_s
{
int val;
struct n_s *next;
}
n_t;
// deletes all elements equal to del in list with head h
n_t * delete(n_t *h, int del);
// returns the first occurrence of find in list with head h, otherwise gives NULL
n_t * find(n_t *h, int find);
n_t *
delFromList(n_t *h, int x)
{
int val;
n_t *el, *posInter;
// empty list case
if (h == NULL)
return NULL;
// first element
val=h->val;
if ( (posInter = find(h -> next,val))
&& (find(posInter -> next, val)))
h = delete(h, val);
// loop from second element
el = h;
while (el -> next)
{
val = el -> next -> val;
// check whether you want to delete the next one,
// and then if you do so, check again on the "new" next one
if ((posInter = find(el -> next -> next, val))
&& (find(posInter -> next, val)))
el -> next = delete(el -> next, val);
// in case you did not delete the nexy node, you can move on
else
el = el -> next;
}
return h;
}
我知道 el->next->next 可能看起来很混乱,但我发现使用诸如“next”、“past”之类的变量不太直观……所以,很抱歉让你头疼。
感谢您的时间。
【问题讨论】:
-
您应该为此指定上下文。如果是课堂作业,通常要么有必须遵守的约束,要么有所学课程的背景来指导应该使用什么解决方案。如果这是一个现实世界的问题,那么应该质疑为什么为此使用链表以及我们可以考虑哪些替代或额外的数据结构。
-
“你有几个非常大的数字,你的记忆不会做”:什么?
-
修改列表的定义是一个选项吗?如果是,您可以有第三个字段来跟踪值“出现”在列表中的时间。那将意味着你将不得不完全改变你的整个程序。
-
当您的列表中有 0、1、2 和 99999 @YvesDaoust 时,声明一个包含 100000 个数字的数组不是一个好主意。也许我应该用一个例子
-
“我发现使用变量不太直观......”:你没有通过招聘测试。