Keep Learning

永远年轻,永远热泪盈眶

LeetCode 82. Remove Duplicates from Sorted List II

问题描述

  • Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.
  • 地址

问题分析

代码实现

  • dummy 节点
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode preNode = dummy;
        ListNode curNode = head;
        while (curNode != null) {
            int val = curNode.val;
            ListNode nextNode = curNode.next;
            if (nextNode != null && nextNode.val == val) {
                while (nextNode != null && nextNode.val == val) {
                    nextNode = nextNode.next;
                }
                preNode.next = nextNode;
                curNode = preNode.next;
            }else {
                preNode = curNode;
                curNode = nextNode;
            }
        }
        return dummy.next;
    }
  • 递归
     public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        if (head.val == head.next.val) {
            ListNode nextNode = head.next;
            while (nextNode != null && nextNode.val == head.val) {
                nextNode = nextNode.next;
            }
            return deleteDuplicates(nextNode);
        }else {
            ListNode resList = deleteDuplicates(head.next);
            head.next = resList;
            return head;
        }
     }
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjxxyz123/article/details/79981032
文章标签: LeetCode 链表
个人分类: LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

LeetCode 82. Remove Duplicates from Sorted List II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭