zoukankan      html  css  js  c++  java
  • 82. Remove Duplicates from Sorted List II

    一、题目

      1、审题

      2、分析

        给出一个有序的整数链表,其中有重复的数字节点,将重复出现的数字节点全部删除,返回新的链表。

    二、解答

      1、思路:

        ①、新建一个伪头结点 fakeHead,next 指向 head,pre 指针指向 fakeHead, cur 指针指向 head;

        ②、如果 cur 的后续节点不为空且 cur 的值等于后续节点的值,说明出现重复节点,则cur 指向后续节点,直到当前 cur 的后续节点值不与 cur 相同

        ③、若 pre.next == cur, 说明节点值不重复出现

        ④、若 pre.next  != cur 说明该节点值重复出现,则删除该值节点。

        ⑤、完成循环遍历

      

    public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null)
                return head;
            
            ListNode fakeHead = new ListNode(0);
            fakeHead.next = head;
            ListNode pre = fakeHead;
            ListNode cur = head;
            
            while(cur != null) {
                while(cur.next != null && cur.val == cur.next.val) {
                    cur = cur.next;
                }
                
                if(pre.next == cur)  // 不重复
                    pre = cur;
                else                 // 重复
                    pre.next = cur.next;
                cur = cur.next;
            }
            
            return fakeHead.next;
        }

      

      递归实现:

    public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null)
                return head;
    
            if(head.next != null && head.next.val == head.val) {
                while(head.next != null && head.next.val == head.val)
                    head = head.next;
                // 查找到有重复的则删除之
                return deleteDuplicates(head.next);
            }
            else {
                head.next = deleteDuplicates(head.next);
            }
            return head;
        }
  • 相关阅读:
    centos8网络连接(1)虚拟机网卡和网络编辑器设置
    centos7离线安装ruby
    centos7安装ruby-2.6.5,简单快捷的下载与安装方式
    redis 4.0.13 -- 集群模式
    活了
    世界无我
    markdown_test
    关于mimikatz在webshell运行
    可用性自动化V3
    关于sqlmap常用
  • 原文地址:https://www.cnblogs.com/skillking/p/9695786.html
Copyright © 2011-2022 走看看