代码实现:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* deleteDuplicates(struct ListNode *head) { if (head == NULL || head->next == NULL) { return head; } struct ListNode *h = malloc(sizeof(*h)); // 创建虚拟头结点 h->next = head; struct ListNode *pre = h; struct ListNode *p = head, *pp = head->next, *pc = NULL; while (pp) { if (p->val != pp->val) { pp = pp->next; pre = p; p = p->next; } else { while (pp && p->val == pp->val) { pp = pp->next; } pre->next = pp; while (p != pp) { pc = p; p = p->next; pc->next = NULL; free(pc); } if (pp) { pp = pp->next; } } } return h->next; }