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; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode p1 = newHead;
ListNode p2 = head;
while(p2 != null){
boolean dup = false;
while(p2.next != null && p2.val == p2.next.val){
dup = true;
p2 = p2.next;
}
if(dup){
p2 = p2.next;
continue;
}
p1.next = p2;
p1 = p1.next;
p2 = p2.next;
}
p1.next = p2;
return newHead.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode l1 = new ListNode(0);
ListNode l2, left, right;
l1.next = l2 = head;
left = l1;
int value = 1;
while(l2.next != null) {
right = l2;
l2 = l2.next;
if(l2.val == right.val) value++;
else {
if(value < 2) {
left.next = right;
left = right;
}
value = 1;
}
}
if(value < 2) left.next = l2;
else left.next = null;
return l1.next;
}
}