zoukankan      html  css  js  c++  java
  • 0082. Remove Duplicates from Sorted List II (M)

    Remove Duplicates from Sorted List II (M)

    题目

    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
    

    题意

    将有序链表中所有值重复的结点删除,只保留值不重复的结点。

    思路

    遍历链表,找到所有值不重复的结点,将其单独取出来依次加入到新链表中。


    代码实现

    Java

    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode ans = null, last = null;
            
            while (head != null) {
                ListNode temp = head.next;
                int count = 0;
                
                // 判断head的值是否重复,并找到下一个值不同的结点
                while (temp != null && temp.val == head.val) {
                    temp = temp.next;
                    count++;
                }
                
                if (count == 0) {
                    head.next = null;		// 将该结点单独取出,断开与之后结点的联系
                    if (ans == null) {
                        ans = head;
                        last = head;
                    } else {
                        last.next = head;
                        last = last.next;
                    }
                }
                
                head = temp;
            }
    
            return ans;
        }
    }
    

    JavaScript

    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var deleteDuplicates = function (head) {
      const dummy = new ListNode()
      let p = dummy
      while (head) {
        if (head.next && head.next.val === head.val) {
          const val = head.val
          while (head && head.val === val) {
            head = head.next
          }
        } else {
          p.next = head
          p = head
          head = head.next
          p.next = null
        }
      }
      return dummy.next
    }
    
  • 相关阅读:
    HERO 3
    office的一些应用,
    网页之间的参数传弟
    一个好的数码网站
    C++遍历中删除std::hash_map元素问题
    【转】Asio与shared_ptr的一些注意事项
    delphi的字节对齐
    paypal的即时付款通知参数列表(PDT)
    vs2010下libevent的使用
    mysql 数据库 left join,right join, inner join 知识
  • 原文地址:https://www.cnblogs.com/mapoos/p/14236548.html
Copyright © 2011-2022 走看看