题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
http://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
设置一个标识,判断时候是否有重复的数字
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if(head==null||head.next==null)
return head;
ListNode dummyNode=new ListNode(-1);
dummyNode.next=head;
ListNode pre=dummyNode, p=head, cur=head.next;
int flag=0;
while (cur!=null){
if(cur.val==p.val){
cur=cur.next;
p.next=cur;
flag=1;
}else {
if(flag==1){
pre.next=cur;
cur=cur.next;
p=p.next;
}else {
pre=pre.next;
p=p.next;
cur=cur.next;
}
flag=0;
}
}
if(flag==1){
pre.next=null;
}
return dummyNode.next;
}
}