/**

  • struct ListNode {
  • int val;
  • struct ListNode *next;
  • };
  • /

class Solution {
public:
/*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode
deleteDuplicates(ListNode* head) {
//1. 链表为空或者结点个数为1时;直接返回结果
if(head == nullptr || head->next == nullptr) return head;
//2. 链表节点个数至少为2时,用两个指针分别指向头两个结点
ListNode * first = head;
ListNode * second = head->next;
while(second != nullptr)
{
if(first->val != second->val)
{
first = first->next; //3. 比较两指针所指结点的值
second = second->next; //若两指针所指节点不相等,将其后移
}else{ //若两指针所指节点相等,后移second直到找到第一个不等于first所指结点的结点或者空结点
while(1){ //让first->next 指向新second,若新second为空,return;若新second不为空,两指针后移
second = second->next; //重复3,直到second为空
if(second->val != first->val || second == nullptr) break;
}
first->next = second;
if(!second) return head;
else{
first = first->next;
second = second->next;
}
}
}
return head;
}
};
//并没有真正删除重复结点,只是让重复结点不在链表上。