• 【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;
        }
    };
  • 相关阅读:
    Linux+postfix+extmail+dovecot打造基于web页面的邮件系统
    各种大型网站技术架构--摘抄
    会php不回缓存行吗?多重实现
    Nutch相关框架视频教程--说明
    Nginx 配置文件模板
    原创:CentOS6.4配置solr 4.7.2+IK分词器
    nutch2.2.1安装部署
    Android View绘制13问13答
    使用 MailOtto 做完美预加载
    ActiveAndroid:活性记录的风格ORM(对象关系映射)
  • 原文地址:https://www.cnblogs.com/luntai/p/5412881.html
Copyright © 2020-2023  润新知