• [LeetCode]Remove Duplicates from Sorted List II


    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    /**
     * 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) {
            ListNode *p,*q,*r; //前中后
            ListNode *newhead=NULL,*n;
            if(head==NULL||head->next==NULL) return head; //空链表,单结点直接返回
            p=head;
            q=p->next;
            r=q->next;
            if(head->val!=head->next->val) newhead=n=head; //若头结点不需要去掉
            if(r==NULL) //两个结点
            {
                if(p->val==q->val) return NULL; 
                else return head;
            }
            while(r)
            {
                if(p->val!=q->val&&q->val!=r->val) //前后不同,新链表加入q
                {
                    if(newhead==NULL)
                    {
                        newhead=n=q;
                    }
                    else 
                    {
                        n->next=q;
                        n=q;
                    }
                }
                p=p->next;
                q=q->next;
                r=r->next;
            }
            //r==NULL
            if(p->val!=q->val) //考虑无头结点情况
            {
                if(newhead==NULL)
                {
                    newhead=q;
                    newhead->next=NULL;
                    return newhead;
                }
                else n->next=q;
            }
            else 
            {
                if(newhead==NULL) return newhead;
                else 
                {
                    n->next=q;
                    n->next=NULL;
                }
            }
            return newhead;
        }
    };
    

      

  • 相关阅读:
    如何闪开安装VS2013必须要有安装IE10的限制
    Java从键盘输入
    Java基本数据类型和关键字
    openssl windows编译 32位&64位
    eclipse代码提示配置
    手动启动Android模拟器
    Android编程中的实用快捷键
    pat1023. Have Fun with Numbers (20)
    pat1022. Digital Library (30)
    pat1020. Tree Traversals (25)
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3521558.html
Copyright © 2020-2023  润新知