LeetCode: Remove Duplicates from Sorted List Solution
Keep jump over next node until values are not equalApproach
Keep jump over next node until values are not equal
Implementation
1var deleteDuplicates = function (head) {2 let node = head34 while (node) {5 while (node.next && node.val === node.next.val) {6 node.next = node.next.next7 }8 node = node.next9 }1011 return head12}
Implementation (recursive)
Note the recursive solution
- it would be less painful to understand if we draw it down
- one thing to remember,
return
statement of first call will run last
1var deleteDuplicates = function (head) {2 if (!head) return null3 head.next = deleteDuplicates(head.next)4 return head.next && head.next.val === head.val ? head.next : head5}
Comments
Loading comments...
Tags
leetcode
linked list
recursion
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Check If String Is a Prefix of Array
Accumulated concatenation and check
Previous Post
LeetCode: Binary Tree Inorder Traversal
Recursive or iterative (stack)