• Leetcode: 82. Remove Duplicates from Sorted List II


    Description

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    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) return NULL;
            ListNode *ptr = head, *pNext = head->next;
            ListNode *res = new ListNode(0);
            ListNode *h = res;
            
            while(pNext){
               if(pNext->val == ptr->val){
                   do{
                        ListNode *tmp = pNext;
                        pNext = pNext->next;
                        delete tmp;
                   }while(pNext && pNext->val == ptr->val);
                  delete ptr;
                  ptr = pNext;
                  if(ptr)
                    pNext = ptr->next;
               }
               else{
                   res->next = ptr;
                   res = res->next;
                   ptr = pNext;
                   pNext = ptr->next;
               }
            }
            
            if(ptr && res && res->val != ptr->val){
                res->next = ptr;
                res = res->next;
            }
            
            if(res)
                res->next = NULL;
            
            return h->next;
        }
    };
    
  • 相关阅读:
    计算机组成原理小结
    selenium基本操作
    selenium实现网易邮箱的登录注册
    如何安装selenium框架
    2020年目标
    个人对软件测试的认识
    java b2b2c电商系统javashop7.2发布
    基于脚本引擎的运费架构分享
    模拟支付宝微信回调
    Javashop电商系统7.2发布
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6953873.html
Copyright © 2020-2023  润新知