前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >剑指offer 删除链表中的重复的结点

剑指offer 删除链表中的重复的结点

作者头像
week
发布2018-12-13 14:51:08
3480
发布2018-12-13 14:51:08
举报
文章被收录于专栏:用户画像用户画像

题目描述

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

代码语言:javascript
复制
package offer.deleteDuplication;

import java.util.HashMap;
import java.util.Map;

public class Solution {
    Map map=new HashMap();

    public void wordCount(ListNode pHead){
        while(pHead!=null){
            int value=pHead.val;
            Integer cnt=(Integer)map.get(value);
            if(cnt==null){
                map.put(value,1);
            }
            if(cnt!=null){
                map.put(value,cnt+1);
            }
            pHead=pHead.next;
        }
    }

    public ListNode deleteDuplication(ListNode pHead)
    {
        ListNode newList=null;
        ListNode newHead=null;
        //统计词频
        wordCount(pHead);
        while(pHead!=null){
            int value=pHead.val;
            Integer cnt=(Integer)map.get(value);
            if(cnt==1){
                ListNode node=new ListNode(value);
                if(newList==null){
                    newList=node;
                    newHead=node;
                }else{
                    newList.next=node;
                    newList=newList.next;
                }
            }
            pHead=pHead.next;
        }
        return newHead;
    }

    public static void main(String[] args) {
        ListNode node1=new ListNode(1);
        ListNode node2=new ListNode(2);
        node1.next=node2;
        ListNode node3=new ListNode(3);
        node2.next=node3;
        ListNode node4=new ListNode(3);
        node3.next=node4;
        ListNode node5=new ListNode(4);
        node4.next=node5;
        ListNode node6=new ListNode(4);
        node5.next=node6;
        ListNode node7=new ListNode(5);
        node6.next=node7;
        node7.next=null;
        Solution solution=new Solution();
        ListNode rs=solution.deleteDuplication(node1);
        while (rs!=null){
            System.out.println(rs.val);
            rs=rs.next;
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年12月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档