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.
删掉重复的节点,这里考虑好特殊情况就好
使用3个指针,指向已经确定没有重复的末尾,正在检查的元素和找重复范围的元素。
var deleteDuplicates = function(head) {
if (!head)
return head;
var dummy = new ListNode(0);
dummy.next = head;
var pre = dummy;
var now = head;
var exam = head.next;
while (exam) {
if (now.val === exam.val) {
while (exam && now.val === exam.val)
exam = exam.next;
pre.next = exam;
if (exam === null) break;
now = exam;
exam = exam.next;
} else {
now = now.next;
exam = exam.next;
pre = pre.next;
}
}
return dummy.next;
};