DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

What is ListNode in JS?

ListNode is a simple data structure commonly used to create linked lists in JavaScript. A linked list is a linear data structure where each element (node) is a separate object. Each node consists of two main parts: the data and a reference (or link) to the next node in the sequence.

In the context of this problem, ListNode represents a node in a singly-linked list. Each ListNode object has two properties:

  • val: Represents the value stored in the node.
  • next: Represents a reference to the next node in the linked list. It's initialized to null by default.

Here's the definition of ListNode used in the addTwoNumbers function:

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val); // Value of the node = (next === undefined ? null : next); // Reference to the next node
Enter fullscreen mode Exit fullscreen mode


Let's say you want to create a linked list with nodes containing values [2, 4, 3]. You can do it like this:

const node1 = new ListNode(2); // Node with value 2 and next pointing to null
const node2 = new ListNode(4); // Node with value 4 and next pointing to null
const node3 = new ListNode(3); // Node with value 3 and next pointing to null

// Link the nodes together to form a linked list: 2 -> 4 -> 3 = node2; = node3;

// Now, node1 represents the head of the linked list
Enter fullscreen mode Exit fullscreen mode

In the addTwoNumbers function, you'll often see linked lists represented and manipulated using these ListNode objects. They provide a straightforward way to construct and traverse linked lists, making it easier to solve problems that involve linked list manipulation.

Disclaimer: This article was created with the help of AI.

Top comments (0)