zoukankan      html  css  js  c++  java
  • 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.

    思路:

    1 先处理头结点是否有相同,若有相同,则更好头结点,使得head指向新的头结点,处理完后,要么返回空链表,要返回的新链表有一个结点或第1,2两个节点不相等。

    2.基于第一步,若新链表只有1个或者2个节点都直接返回,然后用三个指针分别指向第一,二,三个点,接着按常规去除重复结点即可

    代码:

    class Solution{
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            if(head==NULL||head->next==NULL) return head;//空链表或者只要一个结点
    
            //遍历处理头结点是否有重复(删除后,又有新的头结点),处理后,前两个结点不会相等
            ListNode* pheadnext=head->next;
            while (pheadnext!=NULL&&pheadnext->val==head->val)
            {
                while(pheadnext!=NULL&&pheadnext->val==head->val){
                    pheadnext=pheadnext->next;
                }
                if(pheadnext!=head->next) 
                {
                    if(pheadnext==NULL) return NULL;
                    head=pheadnext;
                    pheadnext=head->next;
                }
                else break;
            }
            
            
            ListNode* pre=head;
            ListNode* p=pre->next;
            if(p==NULL) return head;
            ListNode* q=p->next;
         if(q==NULL) return head;
            while(q!=NULL){
                if(p->val==q->val){//比较2,3个结点
                    while(q!=NULL&&p->val==q->val){
                        q=q->next;
                    }
                    pre->next=q;
                    if(q!=NULL){
                       p=q;
                       q=p->next; 
                    }
                    continue;
                }
                pre=pre->next;
                p=p->next;
                q=q->next;
            }
            return head;
        }
    };
  • 相关阅读:
    截取图片中间部分
    chrome调试手机webview中页面
    页面中如何让标点不出现在行首
    jquery checkbox checked 却不显示对勾
    thinkphp 5.x No input file specified 解决
    常用的一些子域名,旁站等查询网站
    Windows应急日志常用的几个事件ID
    fsockopen反弹shell脚本
    LOG日志溯源取证总结
    交互式shell脚本web console
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4241566.html
Copyright © 2011-2022 走看看