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;
        }
    };
  • 相关阅读:
    word上怎么打钩
    POI操作excel常用方法总结
    web.xml中Filter过滤器标签说明
    IDEA使用操作说明(自己总结)
    windows 64位上oracle 11g安装
    List<T>与List<?>的区别
    java分页之假分页
    CDN之Web Cache
    HTTP之缓存技术
    HTTP之Cookie和Session
  • 原文地址:https://www.cnblogs.com/luo-c/p/13033619.html
Copyright © 2011-2022 走看看