数据结构实验:删除队列中的重复元素的完整C语言算法
时间: 2024-03-26 18:42:05 浏览: 14
以下是完整的C语言算法,包含了创建队列、插入元素、删除重复元素等函数:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node, *Queue;
Queue createQueue() {
Queue q = (Queue)malloc(sizeof(Node));
if (q == NULL) {
printf("Failed to allocate memory!\n");
exit(1);
}
q->next = NULL;
return q;
}
void insert(Queue *q, int data) {
Node *p = (Node*)malloc(sizeof(Node));
if (p == NULL) {
printf("Failed to allocate memory!\n");
exit(1);
}
p->data = data;
p->next = NULL;
Node *r = *q;
while (r->next != NULL) {
r = r->next;
}
r->next = p;
}
void printQueue(Queue q) {
if (q == NULL || q->next == NULL) {
printf("The queue is empty.\n");
return;
}
Node *p = q->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void deleteDuplicate(Queue *q) {
if (*q == NULL || (*q)->next == NULL) {
return;
}
Node *p = (*q)->next;
Node *pre = *q;
while (p != NULL) {
Node *q = (*q)->next;
while (q != p) {
if (q->data == p->data) {
pre->next = p->next;
free(p);
p = pre->next;
break;
} else {
q = q->next;
}
}
if (q == p) {
pre = p;
p = p->next;
}
}
}
void destroyQueue(Queue *q) {
if (*q == NULL) {
return;
}
Node *p = (*q)->next;
while (p != NULL) {
Node *tmp = p;
p = p->next;
free(tmp);
}
free(*q);
*q = NULL;
}
int main() {
Queue q = createQueue();
insert(&q, 1);
insert(&q, 2);
insert(&q, 3);
insert(&q, 2);
insert(&q, 4);
insert(&q, 1);
printf("Original queue: ");
printQueue(q);
deleteDuplicate(&q);
printf("Queue after deleting duplicates: ");
printQueue(q);
destroyQueue(&q);
return 0;
}
```
这个算法中,我们先创建一个空队列,然后插入一些元素。接着打印原始队列,调用删除重复元素的函数,再次打印队列,最后销毁队列,释放内存。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)