|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
|
* 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) { |
|
|
|
|
|
let prev = null; |
|
|
|
|
|
let current = head; |
|
|
|
|
|
let found = {}; |
|
|
|
|
|
while (current != null) { |
|
|
|
|
|
if (current.val in found) { |
|
|
|
|
|
prev.next = current.next; |
|
|
|
|
|
current = current.next; |
|
|
|
|
|
} else { |
|
|
|
|
|
found[current.val] = true; |
|
|
|
|
|
prev = current; |
|
|
|
|
|
current = current.next; |
|
|
|
|
|
} |
|
|
|
|
|
} |
|
|
|
|
|
return head; |
|
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
const printLinkedList = (ll) => { |
|
|
|
|
|
while (ll != null) { |
|
|
|
|
|
console.log(ll.val); |
|
|
|
|
|
ll = ll.next; |
|
|
|
|
|
} |
|
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
console.log("Expected: 1->2"); |
|
|
|
|
|
let ll = new ListNode(1, new ListNode(1, new ListNode(2))); |
|
|
|
|
|
console.log(`Got:`); |
|
|
|
|
|
printLinkedList(deleteDuplicates(ll)); |