链表------删除链表中所有重复的结点

题目描述:
给定一个排序链表,要求删除链表中所有的重复结点.(例如: 1->2->2->3->3->4 处理后 1->4)
分析:
使用三个指针front、cur、last,初始时,front = NULL;cur = pHead;last = pHead->next;每一次判断cur->val == last->val .
1. 若相等,则last继续向后移动,直到第一个不等的结点或NULL;
* 当front = NULL 时,若last = NULL,直接返回NULL;若last != NULL,由于front = NULL代表从第一个结点开始到last所指向的结点之前结点都是重复结点,所以要移动pHead,是其指向last,并删除从cur开始到last之前的所有结点;
* 当front != NULL时,使front->next = last;并删除从cur开始到last之前的所有结点
2. 若不等,则cur = cur->next;last = last->next;

struct Node{
    int val;
    struct Node *next;
    Node(int x = 0):val(x), next(NULL){}
};

Node *deleteDuplication(Node *pHead){
    if(pHead == NULL || pHead->next == NULL)
        return pHead;
    Node *front = NULL;//当前结点的前驱
    Node *cur = pHead;//当前结点
    Node *last = pHead->next;//当前结点之后第一个val不同的结点

    while(last != NULL){
        if(cur->val == last->val){
            while(last != NULL && last->val == cur->val)//跳过所有val相同的结点
                last = last->next;
            if(front == NULL){//处理特殊情况,当链表开始的若干结点val都想等时
                if(last == NULL){//此时,又有last = NULL,即链表的所以节点的val都想等,则直接返回NULL
                    return NULL;
                }else{//否则,使pHead=last,删除从cur开始到last之前的所有结点,并使得删除结束时cur=last;
                    pHead = last;
                    Node *tmp = NULL;
                    while(cur != last){
                        tmp = cur;
                        cur = cur->next;
                        delete [] tmp;
                    }
                    last = last->next;//删除结束后,让last指向cur之后的一个结点
                }
            }else{//当front不为NULL,只需要front->next = last, 再删除重复的结点即可
                front->next = last;
                Node *tmp = NULL;
                while(cur != last){
                    tmp = cur;
                    cur = cur->next;
                    delete [] tmp;
                }
                if(last != NULL)
                    last = last->next;
            }
        }else{//即cur->val != last->val,则三个指针都向后移动一步
            front = cur;
            cur = cur->next;
            last = last->next;
        }
    }
    return pHead;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值