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;
        }
    };
  • 相关阅读:
    2. text()方法
    【CS231n】斯坦福大学李飞飞视觉识别课程笔记(十五):神经网络笔记2(下)
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
  • 原文地址:https://www.cnblogs.com/luo-c/p/13033619.html
Copyright © 2011-2022 走看看