Step 2 of 6

33% Complete

Creating Nodes

Learn how to create nodes and build a linked list

Node Structure

The fundamental building block of a linked list is a node. Each node contains two key components:

  • Data: The value stored in the node (e.g., a number, string, or object)
  • Next Pointer: A reference to the next node in the sequence
Node Class Definition
class Node {
constructor(value) {
this.value = value; // The data stored in the node
this.next = null; // Reference to the next node
}
}

Creating Individual Nodes

Let's create some individual nodes and see how they look:

Creating Nodes
// Create three nodes
const node1 = new Node(10);
const node2 = new Node(20);
const node3 = new Node(30);
// At this point, all nodes are isolated
console.log(node1); // Node { value: 10, next: null }
console.log(node2); // Node { value: 20, next: null }
console.log(node3); // Node { value: 30, next: null }
10
node1
20
node2
30
node3

Connecting Nodes

To form a linked list, we need to connect these nodes by setting the next pointer of each node to point to the following node:

Connecting Nodes
// Connect the nodes to form a linked list
node1.next = node2;
node2.next = node3;
// node3.next remains null (end of the list)
// Now we can traverse from node1 to node3
console.log(node1.value); // 10
console.log(node1.next.value); // 20
console.log(node1.next.next.value); // 30

The linked list is empty

Now we have a simple linked list! The nodes are connected in sequence, with each node pointing to the next one. The last node (node3) points to null, indicating the end of the list.

Creating a Linked List Class

While we can manually create and connect nodes, it's more practical to encapsulate this logic in a LinkedList class:

LinkedList Class
class LinkedList {
constructor() {
this.head = null; // Reference to the first node
}
// Add a node to the end of the list
append(value) {
const newNode = new Node(value);
// If the list is empty, make the new node the head
if (!this.head) {
this.head = newNode;
return;
}
// Otherwise, find the last node and add the new node
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
// Print the list values
printList() {
let values = [];
let current = this.head;
while (current) {
values.push(current.value);
current = current.next;
}
return values;
}
}

Now we can use this class to create and manage a linked list more easily:

Using the LinkedList Class
// Create a new linked list
const list = new LinkedList();
// Add nodes to the list
list.append(10);
list.append(20);
list.append(30);
// Print the list
console.log(list.printList()); // [10, 20, 30]

Check Your Understanding

const list = new LinkedList();
list.append(10);
list.append(20);
list.append(30);
list.append(40);
console.log(list.printList());

Next Steps

Now that you know how to create nodes and build a basic linked list, let's move on to learning about insertion operations in the next tutorial.