LeetCode--remove-duplicates-from-sorted-list-ii(链表去重)

题目描述

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

For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.

//Solution 1
//最简单的办法莫过于重新建立一个链表
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head==NULL||head->next==NULL) return head;
        ListNode *newList=new ListNode(-1);
        ListNode *p=newList,*q=head;
        bool isdup=false;
        while(q!=NULL)
        {
            while(q!=NULL&&q->next!=NULL&&q->val==q->next->val)
            {
                isdup=true;
                q=q->next;
            }
            if(isdup) isdup=false;
            else{
                p->next=q;
                p=p->next;
            }
            if(q!=NULL) q=q->next;
        }
       if(p!=NULL) p->next=NULL;
        return newList->next;
    }
};
 
//Solution 2-Recursive
//对于链表首先要想到递归,递归将会很简单
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if(head==NULL||head->next==NULL) return head;
        ListNode *ptr=head;
        if(ptr->val!=ptr->next->val)
        {
            ptr->next=deleteDuplicates(ptr->next);
            return ptr;
        }
        while(ptr!=NULL&&ptr->next!=NULL&&ptr->val==ptr->next->val)
            ptr=ptr->next;
        if(ptr==NULL||ptr->next==NULL) return NULL;
        return deleteDuplicates(ptr->next);
    }
};

拓展版本:

题目描述

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

//non-recursive
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
          if(head==NULL||head->next==NULL) return head;
        ListNode *pre,*pp;
         pre=head;
        pp=head->next;
         while(pp!=NULL)
         {
             while(pp!=NULL&&pp->val==pre->val) 
             {
                 pre->next=pp->next;
                 delete pp;
                 pp=pre->next;
             }
             if(pp==NULL) break;
             pre=pp;
             pp=pre->next;
         }
        return head;
    }
};
 
//recursive
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
            if(head==NULL||head->next==NULL) return head;
        ListNode *del=head->next;
        while(del!=NULL&&head->val==del->val)
        {
            head->next=del->next;
            delete del;
            del=head->next;
        }
        head->next=deleteDuplicates(head->next);
        return head;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值