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
.
基本编程题。
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
ListNode newHead = new ListNode(head.val - 1);
newHead.next = head;
ListNode prePre = newHead;
ListNode pre = head;
ListNode current = head.next;
int preVal = head.val;
while (current != null) {
if (current.val == preVal) {
pre.next = current.next;
current = current.next;
if (pre.val == preVal) {
prePre.next = current;
pre = prePre;
prePre = null;
}
} else {
preVal = current.val;
prePre = pre;
pre = current;
current = current.next;
}
}
return newHead.next;
}