• Leetcode 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.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.


    解题思路: 

    关键是要设置一个dummy作为链表的开始。开始一直想用两个指针,但是一直混乱。看了答案后,答案只用了一个指针,思路一样。关键要理清楚。


    Java code :

    1.

     public ListNode deleteDuplicates(ListNode head) {
            if(head == null) {
                return null;
            }
            
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode p1 = dummy;
    
            while(p1.next!= null && p1.next.next !=null) {
                if(p1.next.val == p1.next.next.val) {
                    int value = p1.next.val;
                    while(p1.next!= null && value == p1.next.val) {
                        p1.next = p1.next.next;
                    }
                }else {
                    p1 = p1.next;
                }
            }
            return dummy.next;
        }Reference:

    2. 九章算法又做了一遍,思路完全一样。2016.01.18

    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            if(head == null) {
                return null;
            }
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            head = dummy;
            while(head.next != null && head.next.next != null) {
                if(head.next.val == head.next.next.val) {
                    int val = head.next.val;
                    while (head.next != null && head.next.val == val) {
                        head.next = head.next.next;
                    }
                } else {
                    head = head.next;
                }
            }
            return dummy.next;
        }
    }

    Reference:

    1. http://www.programcreek.com/2014/06/leetcode-remove-duplicates-from-sorted-list-ii-java/

  • 相关阅读:
    SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client
    Docker 下 nginx + tomcat 负债均衡
    Docker 安装 tomcat 并挂载宿主目录到容器
    Docker 安装 nginx 并挂载宿主目录到容器中
    SpringBoot 常见创建方式
    Java SPI 机制实现解耦
    TCP 粘包问题
    Docker 安装和常用命令
    Docker 安装 ActiveMQ
    INTEL
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4799849.html
Copyright © 2020-2023  润新知