82. Remove Duplicates from Sorted List II

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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        Map<Integer,Integer> map1=new HashMap<Integer,Integer>();
        if(head==null)
            return null;
        ListNode temp=head;
        while(temp!=null)
        {
            if(!map1.containsKey(temp.val))
                map1.put(temp.val,0);
            else
                map1.put(temp.val, 1);
            temp=temp.next;
        }
        ListNode newHead=null;
        temp=head;
        ListNode tail=null;
        
        while(temp!=null)
        {
            if(map1.get(temp.val)==0)
            {
                if(newHead==null)
                    newHead=temp;
                if(tail!=null)
                    tail.next=temp;
                tail=temp;
                temp=temp.next;
                
            }
            else
            {
                temp=temp.next;
            }
        }
        if(tail!=null)
            tail.next=null;
        return newHead;
        
        
    }
}

 

posted @ 2016-07-17 13:08  阿怪123  阅读(145)  评论(0编辑  收藏  举报