题目链接
法一(迭代)
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(0, head);
ListNode pre = dummy, cur = head, next = head.next;
while (cur != null && next != null) {
if (next.val != cur.val) {
pre = pre.next;
}
while (next != null && next.val == cur.val) {
next = next.next;
}
pre.next = next;
cur = next;
if (next != null) {
next = next.next;
}
}
return dummy.next;
}
法二(递归)
public ListNode deleteDuplicates_2(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
if (head.val == next.val) {
while (next != null && head.val == next.val) {
next = next.next;
}
head = deleteDuplicates_2(next);
} else {
head.next = deleteDuplicates_2(next);
}
return head;
}
本地测试
lay.showTitle(82);
Solution82 sol82 = new Solution82();
int[] nums82 = new int[]{1, 1, 1, 2, 3};
ListNode head82_1 = new ListNode();
head82_1 = listOpt.creatListByArray(head82_1, nums82);
listOpt.showList(head82_1);
head82_1 = sol82.deleteDuplicates(head82_1.next);
listOpt.showNoHeadList(head82_1);
ListNode head82_2 = new ListNode();
head82_2 = listOpt.creatListByArray(head82_2, nums82);
listOpt.showList(head82_2);
head82_2 = sol82.deleteDuplicates_2(head82_2.next);
listOpt.showNoHeadList(head82_2);