find the first node in a linked list in javascript

To find the first node in a linked list in JavaScript, you can simply access the head property of the linked list object.

Here's an example:

index.tsx
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }

  // method to add nodes to the linked list
  addNode(data) {
    const newNode = new Node(data);
    if (this.head === null) {
      this.head = newNode;
    } else {
      let currentNode = this.head;
      while (currentNode.next !== null) {
        currentNode = currentNode.next;
      }
      currentNode.next = newNode;
    }
  }
}

const list = new LinkedList();
list.addNode("A");
list.addNode("B");
list.addNode("C");

// Access the first node (head) of the linked list:
console.log(list.head);
655 chars
35 lines

In this example, we define a Node class to represent each node in the linked list, and a LinkedList class to manage the list. The addNode method is used to add new nodes to the list.

To access the first node (head) of the list, we simply use list.head.

gistlibby LogSnag