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

    给定一个有序的链表,将里面出现2次及以上的节点,都删除。

    Input: 1->2->3->3->4->4->5
    Output: 1->2->5

    Input: 1->1->1->2->3
    Output: 2->3


    思路:
    运用3个指针,一根指向当前,一根之前前一个节点,一根指向后一个节点,如果这3个节点的值都不相等,则将当前节点加入结果中,否则继续往下循环。因为头结点没有前一个节点尾节点没有后一个节点,单独处理。

    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            if (!head) return NULL;
            if (head->next == NULL) return head;
            ListNode* res = new ListNode(-1), * tmp = res, * slow = head, * fast = head->next;
            if (head->val != head->next->val) {//处理头结点
                tmp->next = head; tmp = tmp->next;
            }
            head = head->next;
            while (head->next) {
                fast = head->next;
                if (slow->val != head->val && head->val != fast->val) {//三者都不相等
                    tmp->next = head;
                    tmp = tmp->next;
                }
                slow = slow->next;
                head = head->next;
            }
            if (head->val != slow->val) {//处理尾节点
                tmp->next = head;
                tmp = tmp->next;
            }
            tmp->next = NULL;//要将结尾封住
            return res->next;
        }
    };
  • 相关阅读:
    scrapy-redis 分布式爬虫
    爬虫-框架-Scrapy
    MongoDB
    爬虫-请求库之-selenium
    通过位异或来交换a,b的值和通过中间变量交换a,b的值
    位运算
    sizeof运算符
    运算符和表达式(类型转换)
    为什么计算机存储的是二进制补码?
    各种进制的学习与转换
  • 原文地址:https://www.cnblogs.com/luo-c/p/13033619.html
Copyright © 2011-2022 走看看