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.
[code]
/**
* 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) {
if(head==null || head.next==null)return head;
ListNode dummy=new ListNode(0), p=dummy, prev=head, q=head.next;
dummy.next=head;
while(q!=null)
{
boolean unique=true;
while(q!=null && prev.val==q.val)
{
prev=prev.next;
q=q.next;
unique=false;
}
if(unique)
{
p.next=prev;
p=p.next;
}
else p.next=q;
if(q==null)break;
prev=prev.next;
q=q.next;
}
return dummy.next;
}
}