LeetCode 83 Remove Duplicates from Sorted List II

来源:互联网 发布:java html标签转pdf 编辑:程序博客网 时间:2024/06/06 12:31

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.

Given 1->1->1->2->3, return 2->3.

import java.util.HashMap;import java.util.Iterator;import java.util.Map;/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {public ListNode deleteDuplicates(ListNode head) {if (head == null) return head;ListNode dumny = new ListNode(-1);ListNode p = dumny;HashMap<Integer, Integer> hashmap = new HashMap<Integer, Integer>();ListNode cur = head.next;ListNode pre = head;hashmap.put(pre.val, 1);while (cur != null) {if (hashmap.containsKey(cur.val)) {int value = hashmap.get(cur.val).intValue();value++;hashmap.put(cur.val, value);} else {if (hashmap.get(pre.val).intValue() == 1) {p.next = pre;p=p.next;pre.next=null;}hashmap.clear();hashmap.put(cur.val, 1);}pre=cur;cur=cur.next;}if (hashmap.get(pre.val).intValue() == 1)p.next=pre;return dumny.next;}}



0 0
原创粉丝点击