Last active
April 12, 2019 06:03
-
-
Save ZackFox/8642518064e7b32c64c21b82bcb2725b to your computer and use it in GitHub Desktop.
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
function Node(data) { | |
this.data = data; | |
this.next = null; | |
} | |
function sortedInsert(head, data) { | |
let currentNode = head; | |
let prevNode = head; | |
const target = new Node(data); | |
// insert in begining; | |
if(!head || target.data < head.data){ | |
target.next = head; | |
return target; | |
} | |
// insert in middle | |
while(currentNode !== null){ | |
if(currentNode.data > target.data){ | |
prevNode.next = target; | |
target.next = currentNode; | |
return head; | |
} | |
prevNode = currentNode; | |
currentNode = currentNode.next; | |
} | |
// insert in end; | |
prevNode.next = target; | |
return head; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment