用C语言删除单链表中重复的元素
时间: 2023-05-31 21:03:33 浏览: 101
以下是用C语言删除单链表中重复元素的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void deleteDuplicates(struct Node* head) {
struct Node *cur, *pre, *temp;
cur = head->next;
while (cur != NULL) {
pre = cur;
while (pre->next != NULL) {
if (pre->next->data == cur->data) {
temp = pre->next;
pre->next = pre->next->next;
free(temp);
} else {
pre = pre->next;
}
}
cur = cur->next;
}
}
void printList(struct Node* head) {
struct Node* cur = head->next;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
int main() {
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->data = 0;
head->next = NULL;
struct Node* node1 = (struct Node*)malloc(sizeof(struct Node));
node1->data = 1;
head->next = node1;
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
node2->data = 2;
node1->next = node2;
struct Node* node3 = (struct Node*)malloc(sizeof(struct Node));
node3->data = 2;
node2->next = node3;
struct Node* node4 = (struct Node*)malloc(sizeof(struct Node));
node4->data = 3;
node3->next = node4;
printf("Original list: ");
printList(head);
deleteDuplicates(head);
printf("List after deleting duplicates: ");
printList(head);
return 0;
}
```
该程序创建了一个单链表,然后调用 `deleteDuplicates` 函数来删除重复的元素。该函数使用两个指针 `cur` 和 `pre`,其中 `cur` 指向当前要查找重复元素的节点,`pre` 则指向 `cur` 的前一个节点。函数内部使用嵌套循环,第一个循环遍历链表中的每个节点,第二个循环则从 `pre` 开始遍历节点,查找与当前节点 `cur` 的元素是否相同。如果找到了相同的元素,则删除该节点,并更新 `pre` 的 `next` 指针,否则继续向后遍历。最终,函数将删除所有重复的元素。
输出结果如下所示:
```
Original list: 1 2 2 3
List after deleting duplicates: 1 2 3
```
阅读全文