diff --git a/lcci/02.01.Remove Duplicate Node/README.md b/lcci/02.01.Remove Duplicate Node/README.md index 159a271a25dd2..5a3a60855184e 100644 --- a/lcci/02.01.Remove Duplicate Node/README.md +++ b/lcci/02.01.Remove Duplicate Node/README.md @@ -102,6 +102,38 @@ class Solution { } ``` +### **JavaScript** + +```javascript +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ + var removeDuplicateNodes = function(head) { + if (head == null || head.next == null) return head; + const cache = new Set([]); + cache.add(head.val); + let cur = head, fast = head.next; + while (fast !== null) { + if (!cache.has(fast.val)) { + cur.next = fast; + cur = cur.next; + cache.add(fast.val); + } + fast = fast.next; + } + cur.next = null; + return head; +}; +``` + ### **...** ``` diff --git a/lcci/02.01.Remove Duplicate Node/README_EN.md b/lcci/02.01.Remove Duplicate Node/README_EN.md index 1e86e25aa4ce8..d618886cf6087 100644 --- a/lcci/02.01.Remove Duplicate Node/README_EN.md +++ b/lcci/02.01.Remove Duplicate Node/README_EN.md @@ -103,6 +103,38 @@ class Solution { } ``` +### **JavaScript** + +```javascript +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ + var removeDuplicateNodes = function(head) { + if (head == null || head.next == null) return head; + const cache = new Set([]); + cache.add(head.val); + let cur = head, fast = head.next; + while (fast !== null) { + if (!cache.has(fast.val)) { + cur.next = fast; + cur = cur.next; + cache.add(fast.val); + } + fast = fast.next; + } + cur.next = null; + return head; +}; +``` + ### **...** ``` diff --git a/lcci/02.01.Remove Duplicate Node/Solution.js b/lcci/02.01.Remove Duplicate Node/Solution.js new file mode 100644 index 0000000000000..294718cf23288 --- /dev/null +++ b/lcci/02.01.Remove Duplicate Node/Solution.js @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ + var removeDuplicateNodes = function(head) { + if (head == null || head.next == null) return head; + const cache = new Set([]); + cache.add(head.val); + let cur = head, fast = head.next; + while (fast !== null) { + if (!cache.has(fast.val)) { + cur.next = fast; + cur = cur.next; + cache.add(fast.val); + } + fast = fast.next; + } + cur.next = null; + return head; +}; \ No newline at end of file