Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode tmp=head;
while(tmp!=null)
{
if(tmp.next!=null&&tmp.val==tmp.next.val)
{
tmp.next=tmp.next.next;
}
else
{
tmp=tmp.next;
}
}
return head;
}
}
Javascript
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
var tmp=head;
while(tmp!==null)
{
if(tmp.next!==null&&tmp.val==tmp.next.val)
{
tmp.next=tmp.next.next;
}
else
{
tmp=tmp.next;
}
}
return head;
};
优解
Java,用了递归的方法,想法很不错,比较难理解
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
网友评论