Given a sorted linked list, delete all duplicates such that each element appear only once.
这个题目采用了两种方法,一种递归,一种循环,其实原理都差不多。就是一个个找下一个的值是否和当前节点的值相同,若相同则删除,若不同,则继续检查下一个节点。
//方法一
var deleteDuplicates = function(head) {
if(head==null || head.next==null)return head;
if(head.val==head.next.val){
var temp=head.next.next;
//delete head.next;
head.next=temp;
deleteDuplicates(head);
}
else deleteDuplicates(head.next);
return head;
}
// 方法二
var deleteDuplicates = function(head) {
var temp=new ListNode(head.val);
temp=head;
while(temp && temp.next){
if(temp.next.val==temp.val){
var de=temp.next.next;
delete temp.next;
temp.next=de;
}
else temp=temp.next;
}
return head;
}