给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
解题思路
- 当前节点与下一节点相同,cur.next => cur.next.next;
代码实现
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
let cur = head
while(cur && cur.next){
if(cur.val == cur.next.val){
cur.next = cur.next.next
}else{
cur = cur.next
}
}
return head
};
性能
时间复杂度:
空间复杂度: