Skip to content

Instantly share code, notes, and snippets.

@techsin
Created May 16, 2021 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techsin/4432bab7fc08138d7d909b20c8778fa2 to your computer and use it in GitHub Desktop.
Save techsin/4432bab7fc08138d7d909b20c8778fa2 to your computer and use it in GitHub Desktop.
create-target-array-in-the-given-order
/**
* @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