博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode — remove-duplicates-from-sorted-list-ii
阅读量:6445 次
发布时间:2019-06-23

本文共 2708 字,大约阅读时间需要 9 分钟。

/** * Source : https://oj.leetcode.com/problems/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. * * For example, * Given 1->2->3->3->4->4->5, return 1->2->5. * Given 1->1->1->2->3, return 2->3. */public class RemoveDuplicates2 {    /**     * 移除链表中所有重复的元素     *     * @param head     * @return     */    public Node remove (Node head) {        Node dummy = new Node();        dummy.next = head;        Node cur = head;        Node pre = dummy;        boolean duplicated = false;        while (cur != null && cur.next != null) {            if (cur.value == cur.next.value) {                cur.next = cur.next.next;                duplicated = true;            } else if (duplicated) {                // 如果出现重复则移除重复的元素                pre.next = cur.next;                cur = pre.next;                duplicated = false;            } else {                pre = cur;                cur = cur.next;            }        }        if (duplicated) {            pre.next = cur.next;        }        head = dummy.next;        return head;    }    private static class Node  implements Comparable
{ int value; Node next; @Override public String toString() { return "Node{" + "value=" + value + ", next=" + (next == null ? "" : next.value) + '}'; } @Override public int compareTo(Node o) { return this.value - o.value; } } private static void print (Node node) { while (node != null) { System.out.println(node); node = node.next; } System.out.println(); } public Node createList (int[] arr) { if (arr.length == 0) { return null; } Node head = new Node(); head.value = arr[0]; Node pointer = head; for (int i = 1; i < arr.length; i++) { Node node = new Node(); node.value = arr[i]; pointer.next = node; pointer = pointer.next; } return head; } public static void main(String[] args) { RemoveDuplicates2 removeDuplicates2 = new RemoveDuplicates2(); int[] arr = new int[]{1,1,2}; int[] arr1 = new int[]{1,1,2,3,3}; int[] arr2 = new int[]{1,1,2,3,3,3,4,4,5}; print(removeDuplicates2.remove(removeDuplicates2.createList(arr))); print(removeDuplicates2.remove(removeDuplicates2.createList(arr1))); print(removeDuplicates2.remove(removeDuplicates2.createList(arr2))); }}

转载于:https://www.cnblogs.com/sunshine-2015/p/7751781.html

你可能感兴趣的文章
const的各种不同意义
查看>>
Git操作详解
查看>>
I/O 阻塞 中断的注意点
查看>>
什么是HTTP Basic Authentication?
查看>>
python --RecursionError: maximum recursion depth exceeded in comparison
查看>>
Highcharts使用二维数组生成图表
查看>>
spring bean作用域
查看>>
20180416
查看>>
判断一个数是否为素数
查看>>
15年用canvas画的
查看>>
HTML5新特性
查看>>
log4j.appender.AFile.File日志的相对路径
查看>>
乒乓球比赛模拟分析
查看>>
多元线性回归的预测
查看>>
Django——Model
查看>>
servlet体系和生命周期
查看>>
C#前台线程和后台线程区别
查看>>
服务器开发工具
查看>>
个人项目1修改版——自动生成四则表达式
查看>>
更改mysql数据库所在目录
查看>>