单链表中的元素以值非递减有序排列,用C语言写一算法,删除表中所有值相同的多余元素,同时释放被删结点空间。
时间: 2023-05-12 18:07:24 浏览: 132
以下是删除单链表中所有值相同的多余元素的C语言算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
void deleteDuplicates(ListNode *head) {
if (head == NULL) {
return;
}
ListNode *prev = head;
ListNode *cur = head->next;
while (cur != NULL) {
if (cur->val == prev->val) {
prev->next = cur->next;
free(cur);
cur = prev->next;
} else {
prev = cur;
cur = cur->next;
}
}
}
int main() {
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->val = 1;
head->next = (ListNode *)malloc(sizeof(ListNode));
head->next->val = 1;
head->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->val = 2;
head->next->next->next = (ListNode *)malloc(sizeof(ListNode));
head->next->next->next->val = 3;
head->next->next->next->next = NULL;
deleteDuplicates(head);
ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
return 0;
}
```
这个算法的时间复杂度是O(n),其中n是单链表中的元素个数。
阅读全文