题解 | #链表相加(二)#
删除有序链表中重复的元素-I
http://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
思路:
利用set的无重复的特性进行封装,同时使用LinkedHashSet,保证按照顺序存储,且不出现重问题,保证能够去重。
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
Set<Integer>set=new LinkedHashSet<>();
ListNode node=head;
while (node!=null){
set.add(node.val);
node=node.next;
}
ListNode listNode=new ListNode(-1);
ListNode h=listNode;
Iterator<Integer> in=set.iterator();
while (in.hasNext()){
ListNode listNode1=new ListNode(in.next());
listNode.next=listNode1;
listNode=listNode.next;
}
return h.next;
}
}

查看2道真题和解析