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) {
ListNode fake = new ListNode(0);
fake.next = head;
ListNode prev = fake;
ListNode cur = prev.next;
while (cur != null) {
boolean duplicate = false;
int num = cur.val;
while (cur.next != null) {
if (cur.next.val == num) {
duplicate = true;
cur = cur.next;
continue;
} else {
break;
}
}
if (duplicate) {
prev.next = cur.next;
cur.next = null;
cur = prev.next; <span style="color:#ff0000;background-color: rgb(255, 255, 102);">// prev 指针不挪动</span>
} else {
cur = cur.next;
prev = prev.next;
}
}
return fake.next;
}
去年的做法:
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode fake = new ListNode(Integer.MIN_VALUE);
fake.next = head;
ListNode prev = fake;
while (prev.next != null) {
ListNode slow = prev.next;
boolean foundDuplicate = false;
int curVal = slow.val;
ListNode fast = slow.next;
while (fast != null && fast.val == curVal) {
foundDuplicate = true;
fast = fast.next;
prev.next = fast;
}
if (!foundDuplicate) {
prev = prev.next;
}
}
return fake.next;
}