82. Remove Duplicates from Sorted List II
去掉有序链表中的全部重复元素,如[1,1,1,2,3] -> [2,3]
。设置dummy node,双指针跳过重复node
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
while (head != null) {
while (head.next != null && head.val == head.next.val) {
head = head.next;
}
if (pre.next != head) { // there are some duplicated values in between
pre.next = head.next;
} else { // no duplicate values
pre = pre.next;
}
head = head.next;
}
return dummy.next;
}