Created
May 16, 2021 14:09
-
-
Save techsin/4432bab7fc08138d7d909b20c8778fa2 to your computer and use it in GitHub Desktop.
create-target-array-in-the-given-order
This file contains hidden or 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
/** | |
* @param {number[]} nums | |
* @param {number[]} index | |
* @return {number[]} | |
* https://leetcode.com/problems/create-target-array-in-the-given-order/submissions/ | |
*/ | |
function Node(val) { | |
this.val = val; | |
this.next = null; | |
} | |
function LinkedList() { | |
this.root = null; | |
} | |
LinkedList.prototype.addAtIndex = function(index, val) { | |
let counter = 1; | |
let node = this.root; | |
if (index === 0) { | |
const temp = new Node(val); | |
temp.next = this.root; | |
this.root = temp; | |
return; | |
} | |
while(node.next) { | |
if (counter++ === index) break; | |
node = node.next | |
} | |
const newNode = new Node(val); | |
newNode.next = node.next; | |
node.next = newNode; | |
}; | |
LinkedList.prototype.print = function(){ | |
let node = this.root; | |
while(node) { | |
console.log(node.val); | |
node = node.next; | |
} | |
} | |
LinkedList.prototype.toArray = function(){ | |
let node = this.root; | |
const arr = []; | |
while(node) { | |
arr.push(node.val); | |
node = node.next; | |
} | |
return arr; | |
} | |
var createTargetArray = function(nums, index) { | |
const ll = new LinkedList(); | |
for (let i = 0; i < nums.length; i++) { | |
ll.addAtIndex(index[i], nums[i]); | |
} | |
return ll.toArray(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment