每次遇到这种有关重复的,都想用 java中的 list,set临时存一下,有感觉这样相对c是不是开挂了,所以就选择用提供的链表对象构建自己的list判重:
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
ListNode root = head;
ListNode common = null;
ListNode commonRoot = null;
int i = 0;
while(root != null){
int j = 0;
ListNode checkroot = head;
while(j < i){
if(checkroot.val == root.val){
if(commonRoot == null){
commonRoot = new ListNode(root.val);
common = commonRoot;
}else{
commonRoot.next = new ListNode(root.val);
commonRoot = commonRoot.next;
}
break;
}
checkroot = checkroot.next;
j++;
}
root = root.next;
i++;
}
while(containsValue(common,head)){
ListNode temp = head;
head = head.next;
temp.next = null;
}
root = head;
ListNode p = head;
while(root != null){
if(containsValue(common,root)){
p.next = root.next;
root.next = null;
root = p.next;
}else{
p = root;
root = root.next;
}
}
return head;
}
boolean containsValue(ListNode common,ListNode head){
if(head == null){
return false;
}
while(common != null){
if(common.val == head.val){
return true;
}
common = common.next;
}
return false;
}
}