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

    问题描述:

      链表又见链表。把重复的节点全都删掉。

    问题分析:

      我的处理方法是这样的:“ 1 1 2 3 3 4 5 5 6” 明显:将要被留下来的元素都满足一个条件 Pi - 1 != Pi != Pi+1。头节点和尾节点区别对待一下。

    问题解决:

      搞几个指针指来指去的 ,就ok 啦!

    代码如下:

      

    /**
     * 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 NULL;
            else if(head -> next  == NULL) return head;
            ListNode *newHead = NULL;
            ListNode *curP = head, *lastP = NULL, *lastVaildNode = NULL;
            while(curP){
                if(curP == head){//头节点
                    if(curP -> val != curP->next -> val){//head下一个值不同
                        newHead = head;//如果是第一个节点,只需要比较下一个元素
                        lastVaildNode = newHead;
                    }
                }
                else if(curP -> next == NULL){//尾节点
                    if(curP -> val != lastP -> val){
                        if(lastVaildNode == NULL){//头节点为空
                            newHead = curP;
                            lastVaildNode = newHead;
                        }else{
                            lastVaildNode -> next = curP;
                            lastVaildNode = curP;
                        }
                    }
                }else{
                    if(curP -> val != lastP -> val && curP -> val != curP -> next -> val){
                        if(lastVaildNode == NULL){
                            newHead = curP;
                            lastVaildNode = newHead;
                        }else
                            lastVaildNode -> next = curP;
                            lastVaildNode = curP;
                    }
                }
                lastP = curP;
                curP = curP -> next;
            }
            if(lastVaildNode) lastVaildNode -> next = NULL;
            return newHead;
        }
    };
  • 相关阅读:
    复杂对象创建终结者(Builder Pattern)
    创建型模式特立独行的两位大侠
    工厂模式(Factory)
    MAC 相关
    iOS 地图相关
    iOS字体相关
    App跳转系统设置界面
    Mac 模拟慢速网络
    Thread1:EXC_BAD_ACCESS 错误
    iOS 统计App 的代码总行数
  • 原文地址:https://www.cnblogs.com/luntai/p/5412881.html
Copyright © 2011-2022 走看看