/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
// 方法一:利用set容器判断
// 方法二:直接遍历
ListNode* cur = new ListNode(-1);
cur->next = head;
ListNode* ans = cur;
while((cur->next!=nullptr && cur->next->next!=nullptr))
{
// 遇到两个相同的节点
if(cur->next->val == cur->next->next->val)
{
int temp = cur->next->val;
cur = cur->next;
// 除了第一个相同元素,后续相同的都跳过;
while(cur->next && cur->next->val==temp)
cur->next = cur->next->next;
}
else
cur = cur->next;
}
return ans->next;
}
};