首页 > 每天刷一道牛客题霸-第17天-删除链表中重复元素
头像
菜鸟也要飞的高
编辑于 2020-12-23 11:36
+ 关注

每天刷一道牛客题霸-第17天-删除链表中重复元素

题目

https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024?tpId=190&&tqId=35342&rp=1&ru=/ta/job-code-high-rd&qru=/ta/job-code-high-rd/question-ranking

import java.util.*;

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

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public static ListNode deleteDuplicates (ListNode head) {
        LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
        ListNode virtualRoot = new ListNode(0);
        ListNode node = virtualRoot;
        while (head != null){
            if (map.containsKey(head.val)){
                map.put(head.val,-1);
            }else {
                map.put(head.val,1);
            }
            head = head.next;
        }
        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
        for (Map.Entry<Integer, Integer> item : map.entrySet()) {
            if (item.getValue() != -1) {
                node.next = new ListNode(item.getKey());
                node = node.next;
            }
        }
        return virtualRoot.next;
    }
}

全部评论

(1) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

近期精华帖

热门推荐