用C写一个链表查重的代码
时间: 2024-05-15 14:18:53 浏览: 9
好的,我可以帮您编写一个简单的链表查重的代码,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
Node* createNode(int data) {
Node *newNode = (Node *) malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insert(Node **head, int data) {
Node *temp = *head;
if (*head == NULL) {
*head = createNode(data);
return;
}
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = createNode(data);
}
int isDuplicate(Node *head, int data) {
Node *temp = head;
while (temp != NULL) {
if (data == temp->data) {
return 1;
}
temp = temp->next;
}
return 0;
}
void removeDuplicates(Node **head) {
Node *temp1 = *head, *temp2;
while (temp1 != NULL && temp1->next != NULL) {
temp2 = temp1;
while (temp2->next != NULL) {
if (temp1->data == temp2->next->data) {
Node *duplicate = temp2->next;
temp2->next = temp2->next->next;
free(duplicate);
} else {
temp2 = temp2->next;
}
}
temp1 = temp1->next;
}
}
void display(Node *head) {
Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
int n, data;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &data);
if (!isDuplicate(head, data)) {
insert(&head, data);
} else {
printf("Duplicate element found: %d\n", data);
}
}
removeDuplicates(&head);
printf("Linked List after removing duplicates: ");
display(head);
return 0;
}
```
这个代码实现了链表的插入和查重功能,并能够将重复元素从链表中删除。您可以通过输入元素个数和元素的值来测试这个程序。希望能对您有所帮助。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)