class ListNode {
int val;
ListNode next;
}
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode n = head;
while (n.next != null) {
if (n.next.val == n.val) {
n.next = n.next.next; // deletes ListNode
} else {
n = n.next;
}
}
return head;
}
}
- Time Complexity: O(n)
- Space Complexity: O(1)