Created
April 4, 2022 05:54
-
-
Save esase/c32132e7c7a93cd6502dea38c1469ba4 to your computer and use it in GitHub Desktop.
Remove duplicates from sorted list [https://leetcode.com/problems/remove-duplicates-from-sorted-list/]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
if (!head) { | |
return head; | |
} | |
let newList = { | |
val: head.val, | |
next: null, | |
}; | |
let newListReference = newList; | |
let currentReference = head.next; | |
while (currentReference) { | |
if (currentReference.val !== newListReference.val) { | |
// take the item | |
let newItem = { | |
val: currentReference.val, | |
next: null, | |
}; | |
newListReference.next = newItem; | |
newListReference = newItem; | |
} | |
// go to the next node | |
currentReference = currentReference.next; | |
} | |
return newList; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment