C++实现单链表删除重复结点一个不留
时间: 2023-05-21 19:01:03 浏览: 108
可以参考以下代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void deleteDuplicate(Node* head) {
Node* p = head;
while (p != NULL) {
Node* q = p->next;
while (q != NULL && q->data == p->data) {
p->next = q->next;
free(q);
q = p->next;
}
p = p->next;
}
}
int main() {
Node* head = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = NULL;
Node* p = head;
for (int i = 2; i <= 5; i++) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
p->next = node;
p = node;
}
Node* node1 = (Node*)malloc(sizeof(Node));
node1->data = 2;
node1->next = NULL;
p->next = node1;
p = node1;
Node* node2 = (Node*)malloc(sizeof(Node));
node2->data = 4;
node2->next = NULL;
p->next = node2;
p = node2;
printf("Before deleting duplicates: ");
p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
deleteDuplicate(head);
printf("After deleting duplicates: ");
p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
这段代码实现了单链表删除重复结点的功能。具体实现方法是,使用两个指针 p 和 q,p 指向当前结点,q 指向 p 的下一个结点,如果 q 的值等于 p 的值,则删除 q 结点,否则继续遍历。最后输出删除重复结点后的链表。
阅读全文