题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
思路:双指针,一个指针在前面找,找到了判断一下
1)确定是单个不重复结点,就加入到链表,并移动pre。
2)否则就执行while循环跳过当前重复的群体,然后从下一个开始,把pre指针指向此不重复结点,但不移动pre,还需要判断,重复1-2步骤。
public ListNode deleteDuplicates (ListNode head) {
if(head==null || head.next==null){
return head;
}
ListNode h=new ListNode(-1);
h.next=head;
ListNode pre=h;
ListNode cur=head;
while(cur!=null && cur.next!=null){
if(cur.val==cur.next.val){
ListNode tmp=cur.next;
while(tmp!=null && cur.val==tmp.val){
tmp=tmp.next;
}
pre.next=tmp;
cur=tmp;
}else{
pre=pre.next;
cur=cur.next;
}
}
return h.next;
}