题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
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
//头节点为空返回NULL
if(head==null){
return null;
}
//使用List的特新:有序来通过contains方法去重
ArrayList<Integer> list=new ArrayList<>();
ListNode getList=head;
while(getList!=null){
//如果包含该元素则不放入集合
if(!list.contains(getList.val)){
list.add(getList.val);
}
getList=getList.next;
}
//生成链表
Integer first=list.get(0);
ListNode tmp=new ListNode(first);
ListNode returnList=tmp;
int i=1;
for(Integer num:list){
if(i==1){
i++;
continue;
}
ListNode tmpNode=new ListNode(num);
tmp.next=tmpNode;
tmp=tmp.next;
}
return returnList;
}
}
查看14道真题和解析
