Linked Lists
General API to manage linked lists
by Nizar AYED
JavaScript
function ListNode(x) {
this.value = x;
this.next = null;
this.toJSON = function() {
const res = [this.value];
let cur = this.next;
while (cur !== null) {
res.push(cur.value);
cur = cur.next;
}
return res;
}
}
function next(aNode) {
if(aNode.length === 0) return aNode;
return aNode.next;
}
function previous(aNode) {
// Not obvious
}
function head(aNode) {
return aNode;
}
function tail(aNode) {
if(aNode.length === 0) return aNode;
while(aNode.next !== null) {
aNode = aNode.next;
}
return aNode;
}
function length(aList) {
if(aList.length === 0) return 0;
var len = 1;
while(aList.next !== null) {
len++;
aList = aList.next;
}
return len;
}
function append(aNode, toList) {
if(toList.length === 0) toList = aNode;
else toList.next = aNode;
return toList;
}
function prepend(aNode, toList) {
if(toList.length === 0) toList = aNode;
else {
aNode.next = toList;
toList = aNode;
}
return toList;
}
function insert(aNode, toList, atPos) {
}
var a = new ListNode(1);
a.next = new ListNode(2);
a.next.next = new ListNode(3);
console.log(a.toJSON());
console.log(length(a));
console.log(head(a));
console.log(tail(a));