Defining a node in singly linked list
A node is the fundamental building block of a linked list. It holds the actual data item and information of the next node. Multiple nodes, when chained together, make up a single linked list. All the operations on a linked list are performed by manipulating individual nodes and their links. Inserting, deleting, or updating data items in a list are all performed using the list's nodes.
Structure of a node
A singly linked list node has two sections.
- val: The actual data item a node holds. This could be of any type.
- next: This is a reference to the next node in the list
Representation of a singly linked list node
Implementing a node
To define a node in code, we create a Node class that encapsulates the information a singly linked list node must have: data and a reference to the next node. Our class should also have a constructor to initialize the values in nodes at the time of its creation. We can pass in a data value stored in the node and the reference to the next node. We are responsible for linking it to any other node when we see fit.
C++
Java
Typescript
Javascript
Python