82. Remove Duplicates from Sorted List II

栏目: 数据库 · 发布时间: 7年前

内容简介:Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.Example 1:Example 2:

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

难度:medium

题目:给出一 排序 链表,删除所有重复结点,只保留原链表中不重复的结点。

思路:双指针遍历

Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Duplicates from Sorted List II.

Memory Usage: 37.8 MB, less than 0.94% of Java online submissions for Remove Duplicates from Sorted List II.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (null == head) {
            return head;
        }
        
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode prev = dummyHead, ptr = head;
        while (ptr != null && ptr.next != null) {
            if (ptr.val == ptr.next.val) {
                while (ptr.next != null && ptr.val == ptr.next.val) {
                    ptr = ptr.next;
                }
                prev.next = ptr.next;
                ptr = prev;
            } 
            prev = ptr;
            ptr = ptr.next;
        }
        
        return dummyHead.next;
    }
}

以上所述就是小编给大家介绍的《82. Remove Duplicates from Sorted List II》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

高效算法

高效算法

[法] Christoph Dürr、[法] Jill-Jênn Vie / 史世强 / 人民邮电出版社 / 2018-5 / 55.00元

本书旨在探讨如何优化算法效率,详细阐述了经典算法和特殊算法的实现、应用技巧和复杂度验证过程,内容由浅入深,能帮助读者快速掌握复杂度适当、正确率高的高效编程方法以及自检、自测技巧,是参加ACM/ICPC、Google Code Jam 等国际编程竞赛、备战编程考试、提高编程效率、优化编程方法的参考书目。一起来看看 《高效算法》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具