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

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

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:

输入: 1->1->1->2->3
输出: 2->3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-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;
        boolean flag = false;
        while(head != null && head.next != null && head.val == head.next.val) {
            head = head.next;
            flag = true;
        }
        if(flag) head = head.next;
        if(head != null && flag)
            head = deleteDuplicates(head);
        else if(head != null)
            head.next = deleteDuplicates(head.next);
        return head;
    }
}
发布了83 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42317011/article/details/100931608