Remove Duplicates from Unsorted List

题目:

Write code to remove duplicates from an unsorted linked list.

Given 1->3->2->1->4.
Return 1->3->2->4

分析:

不要忘记head == null的情况,所有while(curr.next)的循环都处理不来这种corner case

解法:

public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    public ListNode removeDuplicates(ListNode head) { 
        // Write your code here
        if (head == null) {
            return null;
        }
        HashSet<Integer> LUT = new HashSet<Integer>();
        LUT.add(head.val);
        ListNode curr = head;
        while (curr.next != null) {
            if (LUT.contains(curr.next.val) ) {
                curr.next = curr.next.next;
            } else {
                LUT.add(curr.next.val);
                curr = curr.next;
            }
        }
        return head;
    }  
}

results matching ""

    No results matching ""