删除链表中重复的数字

需要注意下,重复的数字可能是首字符,所在在开头增加一个空结点。

#include<iostream>
using namespace std;
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
    val(x), next(NULL) {
    }
};

class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        if(!pHead)
            return pHead;
        int val = 0;
        ListNode * pFirst = new ListNode(val);
        pFirst->next = pHead;
        ListNode * pre = pFirst;
        pre->next = pHead;
        ListNode * p = pHead;
        while(p && p->next){

            if(p->val == p->next->val){

                while(p->next && (p->val == p->next->val))
                {
                    p = p->next;                        

                }    
                //删除重复的结点,利用前驱结点删除后继结点,一直删除到p结点之前,考虑p节点可能在末尾
                while(pre->next!=p){
                    ListNode* tmp = pre->next;
                    pre->next = pre->next->next;
                    delete tmp;
                }
                //删除p节点
                ListNode * tmp = pre->next;
                pre->next = pre->next->next;
                delete tmp;
                p = pre->next;//不能用p->next因为p已经被删了
            }
            else{  //相邻两个节点不相同
                //pre->next = p;
                pre = pre->next;   
                p = p->next;

            }

        }
        return pFirst->next;        

    }
};

int main(){

    ListNode *pHead = new ListNode(1);
    pHead->next = new ListNode(2);
    pHead->next->next = new ListNode(3);
    pHead->next->next->next = new ListNode(3);
    pHead->next->next->next->next = new ListNode(4);
    Solution s;
    ListNode * result=s.deleteDuplication(pHead);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值