【LeetCode】-Remove Duplicates from Sorted List

来源:互联网 发布:阿里云的cdn怎么样 编辑:程序博客网 时间:2024/04/30 08:20

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.

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

/**
 * 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) {
        ListNode newHead = new ListNode(0);
ListNode tail = newHead;
Set<Integer> set = new HashSet<Integer>();
ListNode p = head;
while( p!=null ){
if( !set.contains(p.val) ){
set.add(p.val);
tail.next = new ListNode(p.val);
tail = tail.next;
}
p = p.next;
}
return newHead.next;    
    }
}

0 0