问题描述
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1:
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
示例2:
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:
链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。
方法一
从第一个元素起,往后开始遍历,删除与之相等的元素
class Solution {
/**
* 选择排序的思路
*/
public ListNode removeDuplicateNodes(ListNode head) {
ListNode pre = head;
while(pre!=null){
ListNode post = pre;
while(post.next!=null){
if(pre.val== post.next.val){
//删除post.next结点
post.next = post.next.next;
}else{
post = post.next;
}
}
pre = pre.next;
}
return head;
}
}
方法二
提供一个集合Set用来记录之前出现过的元素。
class Solution {
/**
* 选择排序的思路
*/
public ListNode removeDuplicateNodes(ListNode head) {
if(head==null){
return head;
}
ListNode pre = head;
HashSet sets = new HashSet();
sets.add(pre.val);
while(pre.next!=null){
if(sets.contains(pre.next.val)){
//删除post.next结点
pre.next = pre.next.next;
}else{
sets.add(pre.next.val);
pre = pre.next;
}
}
return head;
}
}