zoukankan      html  css  js  c++  java
  • *Remove Duplicates from Sorted List

    题目

    Given a sorted linked list, delete all duplicates such that each element appear only once.

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

    题解

    这道题是经典的双指针问题,用两个指针一前一后指向链表。如果两个指针指向的值相等,那么就让第二个指针一直往后挪,挪到与第一个指针不同为止。然后让第一个指针的next指向第二个指针,两个指针同时往后挪,进行下面的操作。

    需要注意,当list的结尾几个node是重复的时候,例如1->2->3->3,那么ptr2会指向null,需要特殊处理,令ptr1.next = null,这样list尾部就不会丢。

    其他情况就不用特殊处理结尾了,因为结尾没有重复值,只须遍历就够了,不用特殊处理尾部。 

    代码如下: 

     1 public ListNode deleteDuplicates(ListNode head) {
     2         if(head == null || head.next == null)
     3             return head;
     4         
     5         ListNode ptr1 = head;
     6         ListNode ptr2 = head.next;
     7         
     8         while(ptr2!=null){
     9             if(ptr1.val == ptr2.val){
    10                 ptr2 = ptr2.next;
    11                 if(ptr2==null)
    12                     ptr1.next = null;
    13             }else{
    14                 ptr1.next = ptr2;
    15                 ptr1 = ptr1.next;
    16                 ptr2 = ptr2.next;
    17             }
    18         }
    19 
    20         return head;
    21     }

    reference: http://www.cnblogs.com/springfor/p/3862042.html

  • 相关阅读:
    [Leetcode] Longest Substring Without Repeating Characters
    [Leetcode] Clone Graph
    [Leetcode] LRU Cache
    行转列
    微信 Demo
    微信开发-step by stemp
    知识库
    SSAS GUID 添加 行计数,非重复计数 等 遇到的莫名其妙的问题
    javascript 前段MVVM 框架
    微信接口开发
  • 原文地址:https://www.cnblogs.com/hygeia/p/4759137.html
Copyright © 2011-2022 走看看