Data structures of this type consist of a series of nodes, each with a value and a reference to the node following it.
const linkedlist = {
head: {
value: 1
next: {
value: 2
next: {
value: 3
next: {
value: 4
next: null
}
}
}
}
}
}
Each node only has one pointer to the node after it.
class ListNode {
constructor(data) {
this.data = data
this.next = null
}
}
class LinkedList {
constructor(head = null) {
this.head = head
}
}
let list = new LinkedList();
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
var node1 = new Node(1);
console.log(node1) // Node { data: 1, next: null }
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
let head;
// Inserts a new Node
function add(new_data) {
let add_node = new Node(new_data);
// Make next Node as head
add_node.next = head;
// Point to new Node
head = add_node;
}
add(1);
add(2);
add(3);
/* In JavaScript, a node will look like this
Node{
data: 3,
next: Node{
data: 2,
next: Node{
data: 1,
next: undefined
}
}
}
*/
class Node {
constructor(val) {
this.data = val;
this.next = null;
}
}
let head;
// Inserts a new Node
function add(new_data) {
let add_node = new Node(new_data);
// Make next Node as head
add_node.next = head;
// Point to new Node
head = add_node;
}
add(1);
add(2);
add(3);
function getLength() {
let count = 0;
let temp = head;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
console.log('Length is :', getLength()) // Length is : 3