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

  • 相关阅读:
    git 学习笔记
    单选框和复选框的样式修改
    es6常用方法
    js混杂笔记
    Entity Framework 学习第一天
    sublime text2的插件熟悉
    近况
    thinkphp ,进行关联模型的时候出现的问题,版本是3.2
    上传图片的权限问题
    今天学习了下,如何破解wifi
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4799849.html
Copyright © 2011-2022 走看看