c++实现单链表删除重复节点
时间: 2023-05-15 22:04:59 浏览: 204
删除单链表中重复结点
4星 · 用户满意度95%
好的,以下是 C 语言实现单链表删除重复节点的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void deleteDuplicates(Node *head) {
Node *current = head;
while (current != NULL) {
Node *runner = current;
while (runner->next != NULL) {
if (runner->next->data == current->data) {
Node *temp = runner->next;
runner->next = runner->next->next;
free(temp);
} else {
runner = runner->next;
}
}
current = current->next;
}
}
int main() {
Node *head = (Node *) malloc(sizeof(Node));
head->data = 1;
head->next = (Node *) malloc(sizeof(Node));
head->next->data = 2;
head->next->next = (Node *) malloc(sizeof(Node));
head->next->next->data = 3;
head->next->next->next = (Node *) malloc(sizeof(Node));
head->next->next->next->data = 2;
head->next->next->next->next = NULL;
printf("Before deleting duplicates: ");
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
deleteDuplicates(head);
printf("After deleting duplicates: ");
current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
return 0;
}
```
希望这个代码能够帮到你!
阅读全文