The topic of dry
There is a linked list in ascending order. Given the head node of the linked list, remove all duplicate elements so that each element appears only once.
Returns a linked list of results, also in ascending order.
Example 1:
Input: head = [1,2]Copy the code
solution
We need three Pointers, the current pointer, the previous pointer, and the next pointer.
If the value of the current pointer is equal to the value of the next pointer, then we have three cases:
- In the first case, we start without the previous prev element, so we point the head node to the current next node and so on
- The second case is that when we have a prev element, we point the prev element to the next node and so on
- The third case is that at the end our next node has no value, so we just point prev to empty and next and return
Execution time: 72 ms, beating 100.00% of users in all JavaScript commits
Memory consumption: 39.7 MB, beating 64.80% of all JavaScript commits
/** * 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) {
/ / double pointer
if (head == null) {
return null
}
let pre = null;
let current = head;
let next = head.next;
while(current ! =null&& next ! =null) {
if (current.val == next.val) {
if (pre == null) {
head = next;
current = head;
next = current.next
} else {
pre.next = next
if (next.next == null) {
return head
} else {
current = next
next = next.next
}
}
} else {
pre = current;
current = current.next;
next = next.next
}
}
return head
};
Copy the code