https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
思路:三指针
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
if (head) {
// 新建一个头结点,便于处理链表的第一个结点
ListNode *newhead = new ListNode(-1), *p = newhead;
newhead->next = head;
// 三指针 分别指向前一结点、当前结点、下一结点
ListNode *pre = newhead, *cur = head, *nxt = cur->next;
while (nxt) {
// 中间值与前后值均不相等 保留当前结点
if (cur->val != nxt->val && pre->val != cur->val) {
p->next = cur;
p = p->next;
}
// 所有指针向前移动一个单位
pre = cur;
cur = nxt;
nxt = nxt->next;
}
// 边界处理
p->next = (pre->val != cur->val) ? cur : nullptr;
return newhead->next;
}
return nullptr;
}
};