Given a sorted linked list, remove all duplicate elements such that each element appears only once.
Example 1:
Input: 1->1->2 Output: 1->2Copy the code
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3Copy the code
Their thinking
- The current node is the same as the next node, cur.next => cur.next-next;
Code implementation
/** * 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
};
Copy the code
performance
Time complexity:
Space complexity: