83. Remove Duplicates from Sorted List
Tags: ‘Linked List’
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
Solution
O(n) time O(1) space 28% 96%
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode curr = head;
while (curr != null) {
ListNode after = curr.next;
while (after != null && after.val == curr.val) {
after = after.next;
}
curr.next = after;
curr = curr.next;
}
return head;
}