zoukankan      html  css  js  c++  java
  • 【LeetCode】82. Remove Duplicates from Sorted List II

    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.

    每次判断下一个节点是否与新链表的尾节点相同,

    若是,删去该值的所有节点,并删去新链表的尾节点

    若不是,则成为新的尾节点

    /**
     * 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 == NULL)
                return head;
            ListNode* newhead = new ListNode(-1);
            ListNode* tail = head;
            ListNode* pretail = newhead;
            pretail->next = tail;
            
            head = head->next;
            while(head != NULL)
            {
                if(tail == newhead || tail->val != head->val)
                {
                    tail->next = head;
                    tail = tail->next;
                    if(pretail->next != tail)
                        pretail = pretail->next;
                    head = head->next;
                }
                else
                {
                    //delete all the same value
                    while(head != NULL && head->val == tail->val)
                        head = head->next;
                
                    pretail->next = NULL;
                    tail = pretail;
                }
                
            }
            tail->next = NULL;
            return newhead->next;
        }
    };

  • 相关阅读:
    linux常用命令
    PHP 魔术方法浅谈
    PHP常用的设计模式
    浅谈Restful
    进程,线程与协程的区别
    http与https的
    get与post的区别
    php连接数据库的两种方式
    DRF框架基本组件之过滤,搜索,排序
    DRF-JWT用户认证
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4148401.html
Copyright © 2011-2022 走看看