Leetcode - 82. 删除排序链表中的重复元素 II
解题思路参考代码中的注释:
/**
* 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;
}
// nextValueNode用于指向第一个值不等于head.val的节点
ListNode nextValueNode = head.next;
while (nextValueNode != null && nextValueNode.val == head.val) {
nextValueNode = nextValueNode.next;
}
// 如果第一个值不等于head.val的节点就是head.next
// 说明head肯定是不重复的节点,此时保留head并继续调用本方法
if (head.next == nextValueNode){
head.next = deleteDuplicates(nextValueNode);
return head;
}
// 否则说明有多个和head的val值相同的节点
// 此时去掉nextValueNode前的所有节点并继续调用本方法
return deleteDuplicates(nextValueNode);
}
}

查看9道真题和解析