用C语言设计算法,删除单链表中相同的元素
时间: 2023-05-30 09:06:16 浏览: 114
1. 定义一个结构体来表示单链表的节点,包含一个数据域和一个指向下一个节点的指针:
```
struct ListNode {
int val;
struct ListNode* next;
};
```
2. 实现删除相同元素的算法,具体步骤如下:
(1)定义一个指针p指向头节点,一个指针q指向p的下一个节点;
(2)循环遍历单链表,直到p指向尾节点为止;
(3)如果p节点的值和q节点的值相同,就将q节点从链表中删除,即令p的next指向q的next,释放q节点的内存空间;
(4)如果p节点的值和q节点的值不同,就将指针p和q都向后移动一个节点;
(5)重复执行步骤(3)和(4),直到p指向尾节点为止。
```
void deleteDuplicates(struct ListNode* head) {
struct ListNode* p = head;
while (p != NULL && p->next != NULL) {
struct ListNode* q = p->next;
if (p->val == q->val) {
p->next = q->next;
free(q);
} else {
p = q;
}
}
}
```
3. 完整代码如下:
```
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
void deleteDuplicates(struct ListNode* head) {
struct ListNode* p = head;
while (p != NULL && p->next != NULL) {
struct ListNode* q = p->next;
if (p->val == q->val) {
p->next = q->next;
free(q);
} else {
p = q;
}
}
}
int main() {
struct ListNode* node1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* node3 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* node4 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* node5 = (struct ListNode*)malloc(sizeof(struct ListNode));
node1->val = 1;
node2->val = 2;
node3->val = 2;
node4->val = 3;
node5->val = 3;
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = node5;
node5->next = NULL;
printf("Before deleting duplicates: ");
struct ListNode* p = node1;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
deleteDuplicates(node1);
printf("After deleting duplicates: ");
p = node1;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
free(node1);
free(node2);
free(node3);
free(node4);
free(node5);
return 0;
}
```
阅读全文