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;
        }
    };
  • 相关阅读:
    生涯路
    事件与window的基本操作
    js操作
    c# 函数
    布局页面CSS
    网页填写的基本操作
    框架集
    网页的基本操作1
    存储与触发器
    常用的函数
  • 原文地址:https://www.cnblogs.com/irun/p/4753484.html
Copyright © 2011-2022 走看看