zoukankan      html  css  js  c++  java
  • 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.

    Example 1:

    Input: 1->2->3->3->4->4->5
    Output: 1->2->5
    

    Example 2:

    Input: 1->1->1->2->3
    Output: 2->3

    这里的策略和83. Remove Duplicates from Sorted List 不同。

    因为这里需要考虑3个以上的连续的重复数字。

    问题可以简化为:

    1.找到重复数字

    2.移除重复数字

    比较麻烦的是,如果第一个数字就是重复的,那么需要重置head。

    比如1->1->2->2这种情况,先移除1,head需要指向2;再移除2,head指向null。

    处理方法是引入一个新的head,并且这个head只需要不和第一个数字重复就好。

      public ListNode DeleteDuplicates(ListNode head)
            {
                if (head == null)
                {
                    return null;
                }
                ListNode myHead = new ListNode(head.val + 1);
                myHead.next = head;
                ListNode node1 = myHead;
                ListNode node2 = node1.next;
                ListNode node1Prev = myHead;
                while (node2 != null)
                {
                    if (node1.val == node2.val)
                    {
                        Remove(node1Prev, node1);
                        node1 = node1Prev.next;
                        node2 = node1?.next;
                    }
                    else
                    {
                        node1Prev = node1;
                        node1 = node2;
                        node2 = node1.next;
                    }
                }
    
                return myHead.next;
            }
    
            private static void Remove(ListNode nodePrev, ListNode node)
            {
                int val = node.val;
                while (node != null && node.val == val)
                {
                    node = node.next;
                }
    
                nodePrev.next = node;
            }
  • 相关阅读:
    价值观
    周记 改
    周记
    C语言问卷调查
    icon踩坑记录
    console.log(a)和console.log(window.a)的区别?
    记录一次微信二次分享的优化过程
    在jQuery中使用自定义属性
    10个JS技巧
    日常工作总结 2019/10/10
  • 原文地址:https://www.cnblogs.com/chucklu/p/10500725.html
Copyright © 2011-2022 走看看