freeCodeCamp/Data Structures/linkedListClassAdd.js

36 lines
728 B
JavaScript
Raw Normal View History

// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/create-a-linked-list-class
function LinkedList() {
var length = 0;
var head = null;
var Node = function (element) {
this.element = element;
this.next = null;
};
this.head = function () {
return head;
};
this.size = function () {
return length;
};
this.add = function (element) {
// Only change code below this line
const newNode = new Node(element);
length++;
let current = head;
if (current === null) {
head = newNode;
return;
}
while (current.next !== null) {
current = current.next;
}
current.next = newNode;
// Only change code above this line
};
}