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;
        }
  • 相关阅读:
    一篇文章了解_docker
    一篇文章了解_接口测试
    一篇文章了解_unittest
    一篇文章了解_selenium
    Python命令行参数sys.argv[]
    Python_pycharm调试模式+使用pycharm给python传递参数
    Python_异常处理、调试
    [问答题]写出下列程序的输出结果:
    [单选题]函数的参数传递包括:
    [单选题]PHP函数,mail($param1, $param2, $param3),其中的$param2参数包含什么?
  • 原文地址:https://www.cnblogs.com/skillking/p/9695786.html
Copyright © 2011-2022 走看看