0
点赞
收藏
分享

微信扫一扫

删除链表中重复元素——Leetcode

狗啃月亮_Rachel 2022-04-21 阅读 96
数据结构

代码实现:

public class DeleteDuplicates {
    //迭代实现
    public ListNode deleteDuplicates1(ListNode head) {
        if (head == null) return null;
        ListNode temp = head;
        ListNode next = head.next;
        while (next != null){
            if (next.val == temp.val){
                next = next.next;
                temp.next = next;
            }else {
                temp = temp.next;
                next = next.next;
            }
        }
        return head;
    }

    //递归实现
    public ListNode deleteDuplicates(ListNode head) {
        if (head ==null || head.next == null) return head;
        ListNode temp = deleteDuplicates(head.next);
        if (temp.val == head.val){
            head.next = temp.next;
        }

        return head;
    }

}

 

举报

相关推荐

0 条评论