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

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list

分析:
思路比较简单,如果元素相等则指向下一个。但是要考虑清楚测试用例的覆盖完备性,最开始笔者就没考虑到两个以上重复的元素出现,只考虑了一个重复的导致错误。添加continue语句那里解决了这个问题。

/**
 * 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;
        ListNode res = head;
        while(head != null && head.next != null) {
            if(head.val == head.next.val) {
                head.next = head.next.next;
                if(head.next != null && head.val == head.next.val)
                    continue;
                head = head.next;
            } else {
                head = head.next;
            }
        }
        return res;
    }
}

重写一遍解法一,貌似有所进步.

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) return head;
        ListNode result = head;
        ListNode temp;
        while (head.next != null) {
            if (head.val == head.next.val) {
                temp = head.next.next;
                head.next = temp;
            } else {
                head = head.next;
            }
        }
        return result;
    }
}

解法二:递归
写递归的思路应该与分治策略紧密连接起来,分治的三步:分解,解决,合并子问题解。那么在程序里就可以按照这三步来写。如下程序第一句if语句是递归的终止条件,第二句则可以看作把链表的每个点都拆开重新指向下一个节点。第二三句起到合并解的作用,将链表连起来。由于是递归,所以求解过程的方向应该是从链表尾往链表头把节点重新连接的。和上面的迭代方向相反。当两个点值相同,这里删除的点,是前一个点.

public ListNode deleteDuplicates(ListNode head) {
    if (head == null || head.next == null) return head;
    head.next = deleteDuplicates(head.next);
    return head.val == head.next.val ? head.next : head;
}

重写一遍解法二:这里删除的点是后面一个点…

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) return head;
        if (head.val == head.next.val) {
            head.next = head.next.next;
            return deleteDuplicates(head);
        } else {
            deleteDuplicates(head.next);
            return head;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值