java 82.从排序列表II(递归).java中删除重复项

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 82.从排序列表II(递归).java中删除重复项相关的知识,希望对你有一定的参考价值。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = pre.next;
        while (cur != null) {
            while (cur.next != null && cur.val == cur.next.val) {
                cur = cur.next;
            } 
            if (pre.next != cur) {
                pre.next = cur.next;
            } else {
                pre = pre.next;
            }
            cur = cur.next;
        }
        return dummy.next;
    }
}
public ListNode deleteDuplicates(ListNode head) {
    if (head == null) return null;
    
    if (head.next != null && head.val == head.next.val) {
        while (head.next != null && head.val == head.next.val) {
            head = head.next;
        }
        return deleteDuplicates(head.next);
    } else {
        head.next = deleteDuplicates(head.next);
    }
    return head;
}
/*
if current node is not unique, return deleteDuplicates with head.next.
If current node is unique, link it to the result of next list made by recursive call. Any improvement?
*/

以上是关于java 82.从排序列表II(递归).java中删除重复项的主要内容,如果未能解决你的问题,请参考以下文章

java 82.从排序列表II(递归).java中删除重复项

java 82.从排序列表II(递归).java中删除重复项

java 82.从排序列表II(递归).java中删除重复项

java 82.从排序列表II(递归).java中删除重复项

LeetCode Java刷题笔记—82. 删除排序链表中的重复元素 II

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