C++实现单链表删除所有重复节点
时间: 2023-05-15 13:05:01 浏览: 58
以下是 C 实现单链表删除所有重复节点的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode *prev = dummy;
struct ListNode *cur = head;
while (cur != NULL) {
while (cur->next != NULL && cur->val == cur->next->val) {
cur = cur->next;
}
if (prev->next == cur) {
prev = prev->next;
} else {
prev->next = cur->next;
}
cur = cur->next;
}
return dummy->next;
}
int main() {
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->next->val = 2;
head->next->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->next->next->val = 3;
head->next->next->next->next = NULL;
struct ListNode *newHead = deleteDuplicates(head);
while (newHead != NULL) {
printf("%d ", newHead->val);
newHead = newHead->next;
}
printf("\n");
return 0;
}
```
如果您有任何问题,请随时问我。