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

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

题目描述:

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

题目链接

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    
    
    public ListNode deleteDuplicates(ListNode head) {
    
    
        if(head == null || head.next == null){
    
     // 结束条件
            return head;
        }
        if(head.val == head.next.val){
    
     // 具有重复元素
            while(head != null && head.next != null && head.val == head.next.val ){
    
     // 跳过重复元素
                head = head.next;
            }
            return deleteDuplicates(head.next); // 进行递归
        }else{
    
     // 不具有重复元素
            head.next = deleteDuplicates(head.next); // 连接
            return head;
        }
    }
}

一般看到是链表的题目都可以先想想是否可以用递归来解决,该题就明显可以利用递归来解决。详细请看代码,有疑问欢迎留言。

猜你喜欢

转载自blog.csdn.net/weixin_43914658/article/details/113852289