LeetCode 82. 删除排序链表中的重复元素 II
原题链接
中等
作者:
LangB
,
2020-11-03 11:14:48
,
所有人可见
,
阅读 246
递归法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = head.next;
if (head.val == p.val) {
// 删除重复出现的数字
while (p != null && head.val == p.val) {
p = p.next;
}
head = deleteDuplicates(p);
} else {
head.next = deleteDuplicates(p);
}
return head;
}
}
迭代法:双指针
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy, q = head;
while (q != null && q.next != null) {
if (q.val == q.next.val) {
while (q.next != null && q.val == q.next.val) {
q = q.next;
}
q = q.next;
p.next = q;
} else {
p = q;
q = q.next;
}
}
return dummy.next;
}
}