4.2 KiB
4.2 KiB
id | title | challengeType |
---|---|---|
587d8252367417b2b2512c67 | Add Elements at a Specific Index in a Linked List | 1 |
Description
Instructions
addAt(index,element)
method that adds an element at a given index. Return false if an element could not be added.
Note: Remember to check if the given index is a negative or is longer than the length of the linked list.
Tests
tests:
- text: Your <code>addAt</code> method should reassign <code>head</code> to the new node when the given index is 0.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.addAt(0,'cat'); return test.head().element === 'cat'}()), 'Your <code>addAt</code> method should reassign <code>head</code> to the new node when the given index is 0.');
- text: Your <code>addAt</code> method should increase the length of the linked list by one for each new node added to the linked list.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.addAt(0,'cat'); return test.size() === 3}()), 'Your <code>addAt</code> method should increase the length of the linked list by one for each new node added to the linked list.');
- text: Your <code>addAt</code> method should return <code>false</code> if a node was unable to be added.
testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); return (test.addAt(4,'cat') === false); }()), 'Your <code>addAt</code> method should return <code>false</code> if a node was unable to be added.');
Challenge Seed
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element) {
this.element = element;
this.next = null;
};
this.size = function() {
return length;
};
this.head = function() {
return head;
};
this.add = function(element) {
var node = new Node(element);
if (head === null) {
head = node;
} else {
var currentNode = head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
// Only change code below this line
// Only change code above this line
}
Solution
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if (head === null){
head = node;
} else {
var currentNode = head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.addAt = function (index, element) {
if (index > length || index < 0) {
return false;
}
var newNode = new Node(element);
var currentNode = head;
if (index === 0) {
head = newNode;
} else {
var previousNode = null;
var i = 0;
while (currentNode && i < index) {
previousNode = currentNode;
currentNode = currentNode.next;
i++;
}
previousNode.next = newNode;
}
newNode.next = currentNode;
length++;
}
}