删除链表中重复的结点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

源代码:

解法一://没有通过

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
import java.util.HashMap;
public class Solution {
    public ListNode deleteDuplication(ListNode pHead) {
        ListNode pre=null,next=null;
        if(pHead==null||pHead.next==null) return pHead;
        pre=pHead;
        //pHead=pHead.next;
        while(pHead!=null&&pHead.next!=null){
            pHead=pHead.next;
            if(pre!=pHead&&pHead!=pHead.next){
                    pre.next=pHead;
                    //m.put(pHead,1);
                }
        }
        return pre;
    }
}

解法二:

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
import java.util.HashMap;
public class Solution {
    public ListNode deleteDuplication(ListNode pHead){
            ListNode pre=null;
            if(pHead==null||pHead.next==null) return pHead;
            pre=pHead;
            HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
            while(pre!=null){//遍历链表,并对每个元素的出现次数计数,注意这里对重复出现的元素的计数方式
                if(hash.containsKey(pre.val)){
                    int cnt=hash.get(pre.val);
                    hash.remove(pre.val);
                    hash.put(pre.val,cnt+1);
                }else{
                    hash.put(pre.val,1);
                }
                pre=pre.next;
            }
            ListNode prenew=pHead;
            ListNode resnode=null;
            ListNode tmp = null;
             boolean  flag=false;
            while(prenew!=null){//遍历链表,对每个节点,判断其出现次数,如果出现次数只有一次,则加入到新的链表中,如果出现次数大于一次,则不加入到链表中
                if(hash.get(prenew.val)==1){
                    if(tmp==null){
                        tmp=prenew;
                        resnode=tmp;//标记头节点
                    }else{
                        tmp.next=prenew;
                        tmp=tmp.next;
                    }
                    flag=true;//如果链表中有元素当且仅当出现过一次,则标记为true
                }
                prenew = prenew.next;
            }
        if(flag==false) return null;//如果链表中所有的元素都是重复出现,则返回空值
            tmp.next=null;//链表中最后一个节点的next域必须设置为空
            return resnode;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值