所以我用 C 语言编写了这个函数,它以一个指针作为参数,该指针存储包含多个数字(整数)的链表的起始地址。然后它返回某个数字在列表中重新出现的次数。例如,7777 将返回 3,因为数字 7 又出现了 3 次。号码8233982还有3等等。 这是代码:
int countRedun(struct digit * start) {
struct digit * front = start;
struct digit * back = start->next;
int i, a[10];
for (i = 0; i < 10; i++) {
a[i] = 0;
}
while (front != NULL) {
while (back != NULL) {
if (front->num == back->num) {
a[front->num] ++;
}
back = back->next;
}
front = front->next;
while (a[front->num] > 0) {
front = front->next;
}
if (front != NULL) {
back = front->next;
}
}
int s = 0;
for (i = 0; i < 10; i++) {
s += a[i];
}
return s;
}
我知道如果列表已排序会更简单,但让我们考虑这种情况。当我尝试运行它时,它显示分段错误。错误在哪里?我的想法是,我有 2 个指针,front 从列表的开头开始,back 从列表的第二个节点开始,检查下一个节点并将它们与存储在地址 front 中的数字进行比较。当 back 到达列表末尾时,front 仅当该地址包含之前未计算过的数字时才会转到下一个节点,否则它将转到下一个节点等。
链表:
struct digit {
int num;
struct digit *next;
};
已修复
int countRedun(struct digit * start) {
struct digit * front = start;
struct digit * back = start->next;
int i, a[10] = { 0 };
while (front != NULL) {
while (back != NULL) {
if (front->num == back->num) {
a[front->num] ++;
}
back = back->next;
}
front = front->next;
int f = 0;
if (front != NULL) {
while (f != 1 && a[front->num] > 0) {
front = front->next;
if (front == NULL) {
f = 1;
}
}
}
if (front != NULL) {
back = front->next;
}
}
int s = 0;
for (i = 0; i < 10; i++) {
s += a[i];
}
return s;}
每次我移动前指针以查找 NULL 情况时都会进行检查,并且它有效。
您的算法似乎比需要的更复杂。使用单个列表迭代计算每个数字出现的次数。之后计算“重复次数”就很简单了。
喜欢:
int countRedun(struct digit * start) {
int a[10] = { 0 };
while (start != NULL) {
a[start->num] ++;
}
int s = 0;
for (int i = 0; i < 10; i++) {
if (a[i]) s = s + a[i] - 1;
}
return s;
}