If there are duplicate nodes in a sorted linked list, please delete the duplicate nodes in the linked list. The duplicate nodes are not retained.
Input: 1->2->3->3->4->4->5 Output: 1->2->5Copy the code
If the virtual header is used in the same way, q = q.ext determines whether the length is 1
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; *} * /
/ * * *@param {ListNode} head
* @return {ListNode}* /
var deleteDuplication = function(head) {
let dummy = new ListNode(-1);
dummy.next = head;
let p = dummy;
while(p.next){
let q = p.next;
while(q && p.next.val === q.val) q = q.next;
// Check whether the length is 1
if(p.next.next === q) p = p.next;
else p.next = q;
}
return dummy.next;
};
Copy the code