C++中,用户输入一组数据(不超过1000个),删除掉其中的重复数据,输出数组中剩余元素个数(假设为n个),并按照原顺序输出所有数字的首次出现。
时间: 2023-05-21 18:06:07 浏览: 52
以下是扮演C知道的AI回答:
可以使用哈希表来实现删除重复数据的操作。首先,创建一个哈希表。然后,依次扫描数组中的每个元素,若该元素还未出现过,则将其加入哈希表中,并且输出该元素。最后,哈希表中元素的个数就是删除重复数据后数组中剩余元素的个数。
以下是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define HASH_SIZE 1007
typedef struct node {
int val;
struct node *next;
} node_t;
node_t *hashTable[HASH_SIZE];
int hash(int x) {
// 哈希函数
return (x % HASH_SIZE + HASH_SIZE) % HASH_SIZE;
}
void insert(int x) {
int h = hash(x);
node_t *p = hashTable[h];
while (p != NULL) {
if (p->val == x) {
return;
}
p = p->next;
}
p = (node_t *) malloc(sizeof(node_t));
p->val = x;
p->next = hashTable[h];
hashTable[h] = p;
printf("%d ", x);
}
int main() {
int n, x;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
insert(x);
}
printf("\n");
int ans = 0;
for (int i = 0; i < HASH_SIZE; i++) {
node_t *p = hashTable[i];
while (p != NULL) {
ans++;
p = p->next;
}
}
printf("%d\n", ans);
return 0;
}
```