题目

image.png

思路

  • 思路一:循环遍历链表,如果出现重复则跳过该值
  • 思路二:递归链表,遇到重复则跳过

    代码

    1. public ListNode deleteDuplicates(ListNode head) {
    2. if (head == null || head.next == null) return head;
    3. ListNode cur = head, nex = head.next;
    4. while (nex != null) {
    5. if (cur.val == nex.val) {
    6. cur.next = nex.next;
    7. nex = nex.next;
    8. } else {
    9. cur = cur.next;
    10. nex = nex.next;
    11. }
    12. }
    13. return head;
    14. }
    15. public ListNode deleteDuplicates(ListNode head) {
    16. if (head == null || head.next == null) return head;
    17. head.next = deleteDuplicates(head.next);
    18. if (head.val == head.next.val) head = head.next;
    19. return head;
    20. }

    删除排序链表中的重复元素