/**
* 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) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prevPrev = dummy, prev = head, curr = head.next;
for( ; curr != null; curr = curr.next) {
if(curr.val != prev.val) {
if(prev.next == curr) {
prevPrev = prev;
} else {
prevPrev.next = curr;
}
prev = curr;
}
}
if(prev.next != null) {
prevPrev.next = null;
}
return dummy.next;
}
}
Time: O(n)
Space: O(1)