import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { // write code here HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(); ListNode last = head; ListNode pre = head; while (last != null) { if (hash != null) { if (hash.containsKey(last.val)) { pre.next = last.next; } else { hash.put(last.val, 1); pre = last; } } last = last.next; } return head; } }
利用hash存储元素来判断是否有重复元素,然后定义两个链表pre,和last,pre是每次循环的last的上一个,主要是用这个处理删除策略,last其实就是当前的元素,当前元素如果和hash的重复则代表上一个节点已经有了,所以将上一个节点的下一个元素置为,当前的节点的下一个节点 pre.next=last.next 这样就完成了删除重复元素的工作