Javascript Solution ✅ || With Explanation 🖋 || O(n)⌚ || Easy to understand
Intuition\n Describe your first thoughts on how to solve this problem. \nThis code is defining a function deleteDuplicates that takes in a singly linked list he
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis code is defining a function deleteDuplicates that takes in a singly linked list head and removes any duplicate nodes from the list.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere is an explanation of the code:\n\nFirst, a dummy node is created with a value of 0 and it is set as the next node of the dummy node. This dummy node will be used to track the head of the list as it is modified. prev is set to dummy and curr is set to head.\n\nA while loop is then entered that will continue until curr is null. Inside the loop, there is another while loop that will continue until curr.next is null or curr.val is not equal to curr.next.val. This inner loop is used to move curr to the last occurrence of a value that is duplicated in the list.\n\nAfter the inner loop, there is an if statement that checks if prev.next is equal to curr. If it is, this means that curr was not a duplicate and prev should be advanced to curr. If prev.next is not equal to curr, this means that curr was a duplicate and prev.next should be set to curr.next to skip over the duplicates.\n\nFinally, curr is advanced to curr.next and the process repeats until curr is null. The modified list, with duplicates removed, is then returned as dummy.next.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this function is O(n), because the function iterates through the linked list once, and performs a constant amount of work on each iteration.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is also O(1), because the function only stores a constant amount of data (the dummy node, the prev and curr pointers) regardless of the size of the input.\n# Code\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar deleteDuplicates = function(head) {\n   let dummy = new ListNode(0)\n    dummy.next = head;\n    let prev = dummy, curr = head;\n    while (curr) {\n        while (curr.next && curr.val == curr.next.val)\n            curr = curr.next\n        if (prev.next == curr)\n            prev = curr\n        else\n            prev.next = curr.next\n        curr = curr.next\n    }\n    return dummy.next\n\n};\n<!--I hope this helps!-->\n<!--Please upvote if you like this solution-->\n\n
['JavaScript']