JSFiddle - React, Tailwind, and code Playground
JavaScript
function LinkedList() {
let length = 0;
let head = {
data: null,
next: null
};
const getLength = function() {
return length;
};
const push = function(data) {
let node;
if (!head.data) {
head.data = data;
length++;
return head.data;
}
node = head;
while (node.next) {
node = node.next;
}
length++;
node.next = { data, next: null };
};
const pop = function() {
let i = 1;
let node;
if (length === 0) {
return null;
} else if (length === 1) {
const data = head.data;
head.data = null;
length--;
return data;
}
node = head;
while (i !== length - 1) {
node = node.next;
i++;
}
const data = node.next.data;
node.next = null;
length--;
return data;
};
const log = function() {
console.log(JSON.stringify(head));
};
return { getLength, push, pop, log };
}
const x = new LinkedList();
x.pop();
x.push(10);
x.push(20);
x.push(30);
x.pop();
x.push(40);
x.log();
console.log(x.getLength());