zoukankan      html  css  js  c++  java
  • 【LeetCode】82

    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.

    Failed solution : 不同于Remove Duplicates from Sorted List,II需要删除所有重复出现的节点,尝试过同时比较三个数,没有成功;

    Solution 1:runtime 12ms

    设置一个新的头节点newhead,比较newhead->next->val与cur->next->val,就变成了比较旧的头节点和第二个节点,直到找到与头节点val不等的节点,将newhead的next指向cur的next;如果cur==newhead->next, 则newhead移向下一个,

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if(!head || !head->next )return head;
            ListNode *newhead=new ListNode(-1);
            newhead->next=head;
            ListNode *cur=head, *pre=newhead;
            while(cur){
                while(cur->next && pre->next->val==cur->next->val){
                    cur=cur->next;
                }
                if(cur==pre->next)
                    pre=pre->next;
                else
                    pre->next=cur->next;
                cur=cur->next;
            }
            return newhead->next;
        }
    };

     Solution 2:runtime 8ms

     设置一个temp变量记录重复节点的val, 删除所有val==temp的节点

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
         ListNode* deleteDuplicates(ListNode* head) {
            if(!head||!head->next)return head;
            ListNode *newhead=new ListNode(-1);
            ListNode *pre=newhead;
            int tmp;
            while(head && head->next){
              if(head->val!=head->next->val){
                  pre->next=head;
                  pre=pre->next;
                  head=head->next;
              }
              else{
                  tmp=head->val;
                  while(head&&tmp==head->val)head=head->next;
              }
            }
            pre->next=head;
            return newhead->next;
        }
    };
  • 相关阅读:
    Lucene.Net 2.3.1开发介绍 —— 二、分词(一)
    控制‘控制台应用程序’的关闭操作
    详解for循环(各种用法)
    敏捷软件开发
    Sql Server的一些知识点
    在SharePoint 2010 中配置Remote Blob Storage FILESTREAM Provider
    使用LotusScript操作Lotus Notes RTF域
    JOpt Simple 4.5 发布,命令行解析器
    John the Ripper 1.8.0 发布,密码破解工具
    PacketFence ZEN 4.0.1 发布,网络接入控制
  • 原文地址:https://www.cnblogs.com/irun/p/4753484.html
Copyright © 2011-2022 走看看