用C语言删除单链表中重复结点,重复结点只保留一个,head是单链表首结点指针
时间: 2023-05-16 15:05:36 浏览: 112
以下是用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 *p = head;
while (p->next != NULL) {
if (p->val == p->next->val) {
struct ListNode *temp = p->next;
p->next = temp->next;
free(temp);
} else {
p = p->next;
}
}
return head;
}
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 = 1;
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;
head = deleteDuplicates(head);
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
return 0;
}
```
我的第二个问题是:lua closure factory 完整代码
阅读全文