Step 2 of 6
33% CompleteCreating 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
class Node {constructor(value) {this.value = value; // The data stored in the nodethis.next = null; // Reference to the next node}}
Creating Individual Nodes
Let's create some individual nodes and see how they look:
// Create three nodesconst node1 = new Node(10);const node2 = new Node(20);const node3 = new Node(30);// At this point, all nodes are isolatedconsole.log(node1); // Node { value: 10, next: null }console.log(node2); // Node { value: 20, next: null }console.log(node3); // Node { value: 30, next: null }
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:
// Connect the nodes to form a linked listnode1.next = node2;node2.next = node3;// node3.next remains null (end of the list)// Now we can traverse from node1 to node3console.log(node1.value); // 10console.log(node1.next.value); // 20console.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:
class LinkedList {constructor() {this.head = null; // Reference to the first node}// Add a node to the end of the listappend(value) {const newNode = new Node(value);// If the list is empty, make the new node the headif (!this.head) {this.head = newNode;return;}// Otherwise, find the last node and add the new nodelet current = this.head;while (current.next) {current = current.next;}current.next = newNode;}// Print the list valuesprintList() {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:
// Create a new linked listconst list = new LinkedList();// Add nodes to the listlist.append(10);list.append(20);list.append(30);// Print the listconsole.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.