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

    分析:将前一个数与后一个数比较,如果不同且出现次数为1,则添加到结果里面。特别要注意最后一个结点:如果与前一个结点相同,则不必添加;如果与前一个结点不同,则必须要添加。运行时间14ms。思考:把line30~32为啥会出现wrong answer?

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* deleteDuplicates(ListNode* head) {
    12         if(!head || !head->next) return head;
    13         
    14         ListNode *result = new ListNode(0);
    15         ListNode *preHead = result;
    16         int times = 1;
    17         while(head->next){
    18             if(head->val == head->next->val) times++;
    19             else{
    20                 if(times == 1){
    21                     result->next = head;
    22                     result = result->next;
    23                 }
    24                 times = 1;
    25             }
    26             head = head->next;
    27         }
    28         if(times == 1){
    29             result->next = head;
    30             result = result->next;
    31         }
    32         result->next = NULL;
    33         
    34         return preHead->next;
    35     }
    36 };
  • 相关阅读:
    scrapy(二)内容获取
    scrapy(一)建立一个scrapy项目
    scrapy(四)使用redis
    scrapy(三)使用mongoDB
    索引处的解码字符串
    Golang竞争状态
    Golang之泛型编程-细节
    区块链学这个就够了-DLT(一)
    Linux日志分析-Ubuntu(一)
    经典博弈-int
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4463591.html
Copyright © 2011-2022 走看看