给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素
思路:想法是用一个指针记录到一定不重复的位置pre,然后,判断是否重复,如果重复了就直到不重复的地方为止,将pre的next更改为此位置
class Solution {
/**
* @param head: head is the head of the linked list
* @return: head of the linked list
*/
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)
return head;
boolean same=false;//用一个标志位记录之前是否重复
ListNode prehead=new ListNode(0);
prehead.next=head;
ListNode pre=prehead;//确保不重复的第一个位置,就是最前面的无实际意义的prehead
ListNode cur=head.next;
ListNode curbefore=head;
while(cur!=null){
if(cur.val!=curbefore.val){//不相等,需要判断之前是否重复过
if(same){//如果重复过,说明这一段不需要考虑了,但是此时的cur指向的位置,并不能确保一定也不重复,需要继续遍历考察,同时撤销重复标志
same=false;
}
else{//如果没有重复,说明curbefore这个元素,肯定不重复,将pre指向它并更新pre
pre.next=curbefore;
pre=pre.next;
}
}
else{//相等,记录重复标志
same=true;
}
cur=cur.next;
curbefore=curbefore.next;
}
if(same)//如果重复,说明末尾的元素出现了一串重复,让pre直接指向null;否则说明没有重复,那么不需要修改指向关系,可以直接输出
pre.next=null;
return prehead.next;
}
}