对顺序读入的n个整数,顺次输出所有不重复的整数,即每个数只能输出一次。C语言
时间: 2024-03-22 14:41:35 浏览: 16
可以使用哈希表来实现这个功能。大致思路如下:
1. 定义一个哈希表,用于存储出现过的整数。
2. 依次读入n个整数,对于每个整数,检查它是否已经在哈希表中出现过。如果没有出现过,则将它添加到哈希表中,并输出它。
3. 完成所有整数的读入和输出后,释放哈希表所占用的内存。
下面是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define HASH_SIZE 10000
typedef struct node {
int key;
struct node *next;
} Node;
void insert(Node **hashTable, int key) {
int index = abs(key) % HASH_SIZE;
Node *p = hashTable[index];
while (p != NULL) {
if (p->key == key) {
return;
}
p = p->next;
}
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->key = key;
newNode->next = hashTable[index];
hashTable[index] = newNode;
printf("%d ", key);
}
void freeHashTable(Node **hashTable) {
for (int i = 0; i < HASH_SIZE; i++) {
Node *p = hashTable[i];
while (p != NULL) {
Node *tmp = p;
p = p->next;
free(tmp);
}
}
}
int main() {
Node *hashTable[HASH_SIZE] = {0};
int n, x;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
insert(hashTable, x);
}
freeHashTable(hashTable);
return 0;
}
```
这个代码中,我们使用了一个链表来解决哈希冲突的问题。当我们需要插入一个新的键值对时,我们首先计算出这个键值对在哈希表中的索引,然后遍历该索引处的链表,查看键值对是否已经存在于链表中。如果存在,则不需要进行任何操作;如果不存在,则将键值对插入到链表的头部,并输出键值对的键。