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;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode safe=new ListNode(0);
safe.next=head;
ListNode pre=safe;
ListNode cur=head;
int val=0;
while(cur!=null&&cur.next!=null){
if(cur.val==cur.next.val){
val=cur.val;
while(cur!=null&&cur.val==val){
pre.next=cur.next;
cur=pre.next;
}
}else{
pre=cur;
cur=cur.next;
}
}
return safe.next;
}
}