每天刷一道牛客题霸-第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;
    }
}
#牛客题霸##题解#
全部评论

相关推荐

点赞 评论 收藏
转发
2 收藏 评论
分享
牛客网
牛客企业服务