删除排序链表中的重复元素(js实现,LeetCode:83)
看到这道题的第一反应是使用快慢指针,之前做过类似的题:删除有序数组中的重复项(js实现,LeetCode:26)原理都是一样,区别是这题需要将重复项删除,所以只需要走一遍单循环就可以实现
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
if(!head) return head
let cur = head
while(cur.next){
if(cur.val===cur.next.val){
cur.next=cur.next.next
}else{
cur=cur.next
}
}
return head
};
这里开一个cur来代替head的原因是因为指针移动的情况下,不开一个新的地址无法找到链表头返回