Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
//思路有点像2号的题,pre类似non_dup_end,但有很大的区别
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head==null) return head;
ListNode newhead = new ListNode(Integer.MIN_VALUE); //设置一个新head,并保证新head的值不会与后面的节点的值重复
newhead.next = head;
ListNode pre = newhead;
ListNode cur = head;
ListNode next = head.next;
boolean dup = false; //用来标志有重复的标志位
while (next!=null) {
if (cur.val!=next.val) {
if (dup) { //处理上次循环遗留下来的重复问题
pre.next = next; //把所有中间重复的节点都删除
dup = false; //重写标志位
}else{
pre = cur; //在删除了中间所有的重复节点之后,pre是不向后移位的,只有不需要处理重复时,才向后移
}
cur = next;
next = next.next;
}
else{ // cur.val==next.val
dup = true; //如果发现了重复,本次循环只是把dup标志位true,并把next向后移一位,pre与cur并不向后移
next = next.next; //对于重复的删除操作是直至向后找到cur!=val时再进行节点删除操作
}
}
if (dup) pre.next = next; //当while循环之后,next为null,若此时dup=true,说明最后几个元素师重复的,但无法进入到while处理
return newhead.next;
}
}